【问题标题】:Flutter Future check returning incorrect value or not awaitingFlutter Future 检查返回不正确的值或不等待
【发布时间】:2022-01-13 01:29:13
【问题描述】:

我在尝试完成这项工作时遇到了困难。我想检查我的用户是否已经存在于我的 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 函数完成才继续。

结果是我的 AuthStatus 始终设置为部分登录。

已经在这里呆了好几个小时了。所以我真的很感激一些关于我在哪里出错的指导。非常感谢。

【问题讨论】:

  • 你不需要await doesUserExist(); 吗?另外,避免在异步函数中使用then - 作为一系列等待,它可能更符合逻辑和可读性

标签: flutter flutter-dependencies


【解决方案1】:

你可以试试这个代码。希望对您有所帮助。

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

【讨论】:

  • 是的,已经解决了。非常感谢。
【解决方案2】:

你可以试试这个代码吗?我认为您的问题是您在 async 功能上使用 then

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

【讨论】:

  • 您好,感谢您的回复。但我仍然得到相同的结果。
猜你喜欢
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
相关资源
最近更新 更多