Firebase Auth状态检查Flutter

时间:2018-04-13 07:51:37

标签: firebase dart firebase-authentication flutter

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

如何在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);
}

2 个答案:

答案 0 :(得分:5)

您也可以像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();
  }
}

答案 1 :(得分:4)

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