Flutter 中的 Firebase 身份验证状态检查 [英] Firebase Auth state check in Flutter

查看:28
本文介绍了Flutter 中的 Firebase 身份验证状态检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我需要设置检查用户是否登录,然后采取相应措施(打开主页或登录屏幕).我只使用电子邮件身份验证.

Currently I need to set up a check whether a user is logged in or not to then act accordingly (open home or log in screen). I'm using only email authentication.

如何在 Flutter 中检查用户的 Firebase 身份验证状态?

这个问题已经有人问过了here,但我无法以这种方式检查身份验证状态:

This question has already been asked here, but I failed to check auth state in this way:

final auth = FirebaseAuth.instance;

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        title: 'MyApp',
        home: (_checkLogin() == true ? new PostAuthScaffold() : new PreAuthScaffold())
    );
  }
}

bool _checkLogin() {
  return !(auth.currentUser == null);
}

推荐答案

您也可以像这样在 initState 中检查您的身份验证状态:

You can also check your auth status inside initState like so:

class CheckAuth extends StatefulWidget {
  @override
  _CheckAuthState createState() => new _CheckAuthState();
}

class _CheckAuthState extends State<CheckAuth> {
  bool isLoggedIn;
  @override
  void initState() {
    isLoggedIn = false;
    FirebaseAuth.instance.currentUser().then((user) => user != null
        ? setState(() {
            isLoggedIn = true;
          })
        : null);
    super.initState();
    // new Future.delayed(const Duration(seconds: 2));
  }

  @override
  Widget build(BuildContext context) {
    return isLoggedIn ? new Home() : new LoginScreen();
  }
}

这篇关于Flutter 中的 Firebase 身份验证状态检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆