【问题标题】:Firebase Auth state check in FlutterFlutter 中的 Firebase 身份验证状态检查
【发布时间】:2018-09-23 12:19:04
【问题描述】:

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

如何在flutter中检查用户firebase身份验证状态?

这个问题已经被问到here,但是我没有通过这种方式检查身份验证状态:

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

【问题讨论】:

    标签: firebase dart firebase-authentication flutter


    【解决方案1】:

    您还可以在initState 中检查您的身份验证状态,如下所示:

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

    【讨论】:

    • 返回“断言失败:布尔表达式不能为空”错误。我是否应该在每次用户登录或注销时手动更改 isLoggedIn 值并将该值存储在 Shared Preferences 中?
    • 那是我忘记初始化值了,我更新了代码
    【解决方案2】:

    怎么样

    FirebaseAuth.instance.onAuthStateChanged.listen((user) {
      setState(() => isAuthenticated = user != null);
    }) 
    

    【讨论】:

    • 尝试了这种方法,也以防万一“user.email!= null”,但它似乎不起作用 - 重新打开应用程序后它仍然会返回登录页面。谢谢
    • "重新打开应用后仍然返回登录页面。"为什么你认为这与我发布的代码有关?
    • 我使用 isAuthenticated 变量打开适当的页面:主页:_isAuthenticated == true ?新的 HomeScreen() :新的 LogInScreen()。这是一种错误的做法吗?
    • 从那个代码sn-p很难说。可能是对的,但如果返回预期结果,您应该测试上面的代码。
    • 是的,我可以成功注册并登录(感谢您对我上一个问题的回答),但是如果我在登录后关闭我的应用程序然后再次打开它 - 会弹出登录屏幕再次(而不是预期的主屏幕)
    猜你喜欢
    • 2017-12-09
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多