Flutter: How to listen to the FirebaseUser is Email verified boolean?

后端 未结 8 723
走了就别回头了
走了就别回头了 2021-01-01 20:38

My Idea: I want to use the Firebase Auth Plugin in Flutter to register the users. But before they can access the App, they have to verify their Email addres

8条回答
  •  暖寄归人
    2021-01-01 21:13

    True. None of the FirebaseAuth idTokenChanges() , authStateChanges() or userChanges() will send you an event if the user verifies their email. I'm using a combination of the methods to get an email verification update in my app and it seems to be working well.

    First I check the status in the initState() method and start a timer if email is not verified

      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
    
        //Get Authenticated user
        user = context.read().currentUser();
        _isEmailVerified = user.emailVerified;
        if (!_isEmailVerified) _startEmailVerificationTimer();
    
        }
    

    I also listen for app background/foreground events in case the user happens to leave the app to confirm their email ( If you also do this, add WidgetsBindingObserver to your class)

     @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        if (state == AppLifecycleState.resumed) {
          user = context.read().reloadCurrentUser();
          if (user.emailVerified) {
            setState(() {
              _isEmailVerified = user.emailVerified;
            });
            timer?.cancel();
          } else {
            if (!timer.isActive) _startEmailVerificationTimer();
          }
        } 
      }
    

    This is the _startEmailVerificationTimer() method

     _startEmailVerificationTimer() {
        timer = Timer.periodic(Duration(seconds: 5), (Timer _) {
          user = context.read().reloadCurrentUser();
          if (user.emailVerified) {
            setState(() {
              _isEmailVerified = user.emailVerified;
            });
            timer.cancel();
          }
        });
      }
    

    Don't forget to dispose the timer

      @override
      void dispose() {
        timer?.cancel();
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    

    My Firebase User methods in case anyone is interested:

      User currentUser() {
        return _firebaseAuth.currentUser;
      }
    
      User reloadCurrentUser() {
        User oldUser = _firebaseAuth.currentUser;
        oldUser.reload();
        User newUser = _firebaseAuth.currentUser;
        return newUser;
      }
    

提交回复
热议问题