如何检查 Flutter Firestore 中是否存在用户文档?

How to check if a user document exists in Flutter Firestore?

如果用户通过 StreamBuilder 根据其用户 ID ('uid') 在 'users' 集合下的 Firestore 中拥有文档,我将尝试在用户通过身份验证后添加检查。

我遇到的问题是,当我 运行 我的代码时,它按预期工作,但几秒钟后,即使文档不存在,它也会重定向到 'UserHomeScreen'。我该如何纠正这个问题,这样没有用户文档的用户就不会被推送到我的 'UserHomeScreen'?

这是我的代码:

class UserStream extends StatelessWidget {
  const UserStream({Key? key}) : super(key: key);
  

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseFirestore.instance.collection('users').doc('uid').snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return const UserHomeScreen();
        } else {
          return const SignUpNewUser();
        }
      },
    );
  }
}

当异步调用完成时,snapshot.hasData 为真。即使文档不存在,一旦确定,snapshot.hasData 仍然为真。

为确保文档存在,您还需要检查:

if (snapshot.hasData && snapshot.data!.exists) {
  ...

这也显示在 handling one time reads 的文档中。