Firebase Auth state check in Flutter

早过忘川 提交于 2019-12-30 02:24:45

问题


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.

How to check user firebase auth state in flutter?

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

回答1:


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



回答2:


What about

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


来源:https://stackoverflow.com/questions/49811909/firebase-auth-state-check-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!