[英]Flutter Future check returning incorrect value or not awaiting
我在嘗試完成這項工作時遇到了困難。 我想檢查我的用戶是否已經存在於我的 Firestore 數據庫中。 該記錄確實存在,但是由於某種原因我的異步檢查沒有返回該記錄。 這是我的代碼:
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;
}
請注意有兩個打印語句。 print(userFound) 顯示為 true,這是正確的。 print(fullyLoggedIn) 顯示為 false,這是不正確的。
我還看到 print(userFound) 發生在 print(fullyLoggedIn) 之后。 所以錯誤一定是它沒有等到 checkMemberExists function 完成后再繼續。
結果是我的 AuthStatus 始終設置為部分登錄。
已經在這里待了好幾個小時了。 所以我真的很感激一些關於我在哪里出錯的指導。 太感謝了。
你可以試試這個代碼嗎? 我認為您的問題是您在異步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;
}
你可以試試這段代碼。 希望對您有所幫助。
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
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.