Home > database >  Flutter Future check returning incorrect value or not awaiting
Flutter Future check returning incorrect value or not awaiting

Time:12-08

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.

CodePudding user response:

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

CodePudding user response:

You can try this code ? I think your issue is you are use then on async function

  Future<bool> checkMemberExist(String memberId) async {
    bool userFound = false;
    final member = await _firestore.collection('members').doc(memberId).get();
    userFound = member.exists;
    print(userFound);
    return userFound;
  }
  • Related