Solution 1 :
The problem is that get()
is asynchronous and returns immediately before the query is complete. Your success listener will not be invoked until some time later. You get no guarantee how long that takes.
Your second bit of code is probably trying to access userExists
before it was assigned in the listener, which means it will see the default value of false
.
Since you don’t know how long the get()
will take, you should look into using a LiveData to capture the results, and write code to observe that LiveData to know when query query completes.
Solution 2 :
You can use the .where( field, isEqualTo: query). This might be useful to you.
checkExists(String query) async {
QuerySnapshot checker = await userRef
.where('uid', isEqualTo: query)
.get();
chkr.docs.forEach((doc) {
if (doc.exists) {
print('Exists');
print(doc.get('uid'));
}else {
print('false');
}
});
}
Then, if you are using a button, you can use onPressed: () => check(yourQuery).
Problem :
I have created a function in my viewModel to check if the document already exists in firestore database
fun isUserRegistered() {
val userRef = firebaseRepository.firestoreDB.collection("users").document(firebaseRepository.userid.toString())
userRef.get()
.addOnSuccessListener { document ->
if (document != null)
userExists = true
}
}
if the document exists the value of the boolean userExists should change from ‘false’ to ‘true’
and in my Fragment I`m calling the function in the onActivityResultMethod
viewModel.isUserRegistered()
if(viewModel.userExists)
findNavController().navigate(R.id.action_startFragment_to_mainFragment)
the value of userExists is always ‘false’. Where did I make the mistake?