Ad

Flutter Future Check Returning Incorrect Value Or Not Awaiting

- 1 answer

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.

Ad

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
   }
});
Ad
source: stackoverflow.com
Ad