Firebase Auth state check in Flutter

后端 未结 2 1414
栀梦
栀梦 2020-12-15 13:38

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.

相关标签:
2条回答
  • 2020-12-15 14:25

    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();
      }
    }
    
    0 讨论(0)
  • 2020-12-15 14:27

    What about

    FirebaseAuth.instance.onAuthStateChanged.listen((user) {
      setState(() => isAuthenticated = user != null);
    }) 
    
    0 讨论(0)
提交回复
热议问题