【问题标题】:check authentication state of User using FirebaseAuth in Flutter在 Flutter 中使用 FirebaseAuth 检查用户的身份验证状态
【发布时间】:2020-12-19 11:34:04
【问题描述】:

我知道存在这样的问题,但其中充满了过时和不正确的答案。新的FlutterFire 文档使用 Streams 来获取用户的状态,我很难尝试执行这样一个微不足道的任务,因为我对 Flutter 和 Dart 缺乏经验。这是过时问题的答案和参考。

我期待 StreamBuilder 的答案,这里是我写到现在的代码:

@override
  Widget build(BuildContext context) {
    return StreamBuilder(
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) { 
        if(snapshot.hasData) {
          print("data exists");
          return snapshot.data ? First() : SignIn();
        }
        else {
          return SignIn();
        }
      },
      future: isUserLoggedIn(),
    );
  }

Stream<bool> isUserLoggedIn() {
    FirebaseAuth.instance
        .authStateChanges()
        .listen((User user) {
      if (user == null) {
        print('User is currently signed out!');
        // return false; ???
      } else {
        print('User is signed in!');
        // return true; ???
      }
    });
  }

编辑:

Firebase 身份验证使您能够通过 >Stream 实时订阅此状态。一旦被调用,该流将提供用户当前身份验证状态的即时事件,然后在身份验证状态发生变化时提供后续事件。

FlutterFire Auth Doc

【问题讨论】:

  • StreamBuilder 不接受 future 属性,它需要 stream 属性。

标签: firebase flutter dart firebase-authentication stream


【解决方案1】:

isUserLoggedIn() 没有返回任何类型的流。我建议只听实际的authStateChanges() 流。

  Widget build(BuildContext context) {
    return StreamBuilder<User>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (BuildContext context, AsyncSnapshot<User> snapshot) { 
        if(snapshot.hasData) {
          print("data exists");
          return First();
        }
        else {
          return SignIn();
        }
      },
    );
  }

【讨论】:

  • 我在问题中写的代码已经过时了。
  • 我要求更新的代码是为了让更多的新手开发人员不会偶然发现以前的帖子有错误和过时的答案。你给出的答案是正确的!
  • 这似乎适用于 Android,但对于 Web,hasData 永远不会触发
  • @Benjamin - 就我而言,“FirebaseAuth.instance.authStateChanges”流为我提供了登录和注销事件,但不适用于创建帐户。 - 有什么需要说明的吗?
猜你喜欢
  • 1970-01-01
  • 2018-09-23
  • 2021-07-12
  • 2017-12-05
  • 1970-01-01
  • 2016-12-23
  • 2017-09-23
  • 1970-01-01
  • 2020-09-22
相关资源
最近更新 更多