【问题标题】:How to implement onAuthStateChanged() in flutter?如何在 Flutter 中实现 onAuthStateChanged()?
【发布时间】:2020-07-19 06:31:38
【问题描述】:
<https://stackoverflow.com/a/32254702/10026969>  I am not getting this.

@override
void initState()  async{
// TODO: implement initState
super.initState();

FirebaseUser user = await _auth.currentUser();
if(user!=null){
  print('Already logged in with email  '+ user.email);
  // go to welcome screen
 }
}

我无法继续使用onAuthStateChange,如何让用户保持登录状态直到他退出,如果有人知道如何实现这个,请帮助。

【问题讨论】:

  • 如果答案对您有帮助,请点赞并标记为正确,谢谢!

标签: firebase flutter dart firebase-authentication


【解决方案1】:

如果你想在flutter中使用onAuthStateChange,那么试试下面的方法:

var auth = FirebaseAuth.instance;
auth.onAuthStateChanged.listen((user) {
if (user != null) {
  print("user is logged in");
} else {
  print("user is not logged in");
   }
});

onAuthStateChanged 返回一个Stream,因此您可以使用listen() 继续监听任何更改。

https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_auth/firebase_auth/lib/src/firebase_auth.dart#L23

【讨论】:

    【解决方案2】:

    所以 onAuthStateChanged() 返回一个 Stream。 https://pub.dev/documentation/firebase_auth/latest/firebase_auth/FirebaseAuth/onAuthStateChanged.html

    您可以使用 StreamBuilder 侦听此流中的所有事件。根据从构建器函数返回的 AsyncSnapshot,您可以检查它是否有数据。

    1. 创建您的 FirebaseAuth 对象。该对象具有 onAuthStateChanged() 的属性。
    2. 将属性 _auth.onAuthStateChanged() 传递给您的 StreamBuilder。

    伪示例代码:

    final FirebaseAuth _auth = FirebaseAuth.instance;
    
    Center(
      child: StreamBuilder(
        stream: _auth.onAuthStateChange(),
        builder: (context, asyncSnap) {
          //no available data yet
          if(!asyncSnap.hasData) {
            return Text("No data available yet.");
          } else if(asyncSnap.hasError) {
            return Text("Error");
          } else {
            //Use a switch here over all of the types of state coming back.
            return Text("Data from Snapshot: ${asyncSnap.data}");
          }
        }
      )
    )
    

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 2023-04-03
      • 2019-03-19
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2021-04-03
      • 2019-05-29
      相关资源
      最近更新 更多