how to check if data exists in a document firebase flutter

I am trying to check if user user input data exists in firebase when user presses this button.

if it's exist go to signUp

This is the button


                          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');
                                } 

This is the Text field

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

Solution 1:

You dont seem like you would be needing a setState call at all.

Just use an async function for the onPressed callback and use await to get your data asynchronously.

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');
  }
}