如何检查文档中是否存在数据 firbase flutter

时间:2021-05-24 15:25:05

标签: firebase flutter dart

当用户按下此按钮时,我正在尝试检查用户输入数据是否存在于 firebase 中。

如果存在就去注册

这是按钮


                          onPressed: () {
                            setState(() {
                              if (studentId == null){
                                 //error message 
                              }else {
                                _firebase
                                    .collection("university_ids")
                                    .doc(studentId)
                                    .get()
                                    .then((doc) {
                                  if (doc.exists) {
                                    setState(() {
                                      isExists = true;
                                    });
                                  } else {
                                    setState(() {
                                      isExists = false;
                                    });
                                  }
                                });
                                if (isExists) {
                                  Navigator.pushNamed(
                                      context, 'sign_up_screen');
                                } 

这是文本字段

                            onChange: (value) {
                              setState(() {
                                studentId= value;
                              });
                            },
                        

1 个答案:

答案 0 :(得分:2)

您似乎根本不需要 setState 电话。

只需将 async 函数用于 onPressed 回调并使用 await 异步获取数据。

onPressed: () async {
  if (studentId == null) { //error message }
  else {
     var doc = await _firebase.collection("university_ids").doc(studentId).get();
                              
     if (doc.exists) Navigator.pushNamed(context, 'sign_up_screen');
  }
}