Flutter Future Check Returning Incorrect Value Or Not Awaiting
I'm having difficulties trying to make this work. I want to check if my user already exists or not in my Firestore database. The record does exist, however my async check is not returning that for some reason. Here is my code:
void doesUserExist() async {
fullyLoggedIn = await _members.checkMemberExist(_userId);
}
setAuthStatus() async {
_auth.getCurrentUser().then((user) {
setState(() {
if (user != null) {
_userId = user.uid;
}
if (user?.uid == null) {
authStatus = AuthStatus.NOT_LOGGED_IN;
} else {
doesUserExist();
print(fullyLoggedIn);
if (fullyLoggedIn) {
authStatus = AuthStatus.LOGGED_IN_FULLY;
} else {
authStatus = AuthStatus.LOGGED_IN_PARTIAL;
}
}
});
});
}
Future<bool> checkMemberExist(String memberId) async {
bool userFound = false;
await _firestore.collection('members').doc(memberId).get().then((member) {
if (member.exists) {
userFound = true;
}
});
print(userFound);
return userFound;
}
Please note there are two print statements. The print(userFound) is showing true which is correct. The print(fullyLoggedIn) is showing false which is incorrect.
I am also seeing that the print(userFound) is happening after the print(fullyLoggedIn). So the error must be that it is not waiting until the checkMemberExists function is done before continuing.
The result is that my AuthStatus is always set to Partially Logged in.
Been at this for many hours now. So I'd really appreciate some guidance on where I am going wrong with this. Thank you so much.
Answer
You can try this code. Hope its help you.
Future<bool> doesUserExist() async {
return fullyLoggedIn = await _members.checkMemberExist(_userId);
}
doesUserExist().then((fullyLoggedIn) {
print(fullyLoggedIn);
if (fullyLoggedIn) {
authStatus = AuthStatus.LOGGED_IN_FULLY; //wrap it with setState if its a state
} else {
authStatus = AuthStatus.LOGGED_IN_PARTIAL; //wrap it with setState if its a state
}
});
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?