Firebase query inside the If-statement in flutter
222
I faced the same issue once, this is because of foreach loop which doesn't work properly with async functions, try replacing foreach with for in loop,
try this.
await firestoreInstance.collection('quizes').get().then((querySnapshot) async{
for (final doc in querySnapshot.docs) {
tempPin = doc.get('quizPin').toString();
quizDocId = doc.get('quizid').toString();
if (tempPin.contains(pin) && tempPin == pin){
final sessionCheck = await firestoreInstance.collection('activesessions').get();
if(sessionCheck.docs.length == 0){
setState(() {
_error = "session is not active";
});
print(_error);
}}
else
{
setState(() {
_error = "You have Entered an Invalid Pin";
});
print(_error);
}
}
Author by
Elam
Updated on January 03, 2023Comments
-
Elam over 1 year
I am trying to do few checkpoint in my app, i am getting the data from the firebase and with that response i am adding a checkpoint based on this checkpoint i am trying to retrieve data from firebase and display it.
The issue i am facing is that when i using the firebase query inside the if-else statement both the statement are getting executed, since i have used the async for firebase it first executes the else statement.
how to overcome this issue, can anyone help me on this issue.
Below is my code.
await firestoreInstance.collection('quizes').get().then((querySnapshot) { querySnapshot.docs.forEach((doc) async { tempPin = doc.get('quizPin').toString(); quizDocId = doc.get('quizid').toString(); if (tempPin.contains(pin) && tempPin == pin){ final sessionCheck = await firestoreInstance.collection('activesessions').get(); if(sessionCheck.docs.length == 0){ setState(() { _error = "session is not active"; }); print(_error); }} else { setState(() { _error = "You have Entered an Invalid Pin"; }); print(_error); }
my console output for this code
flutter: Invalid Pin flutter: Invalid Pin flutter: session is not active
-
Elam over 2 yearsSorry for the late response. In this code both the if and else statement is executed, dont know y both the statement is executing.
-
Sahil Hariyani over 2 yearsHi @Elam, I have updated the code. Can you try it once?