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

后端 未结 8 712
走了就别回头了
走了就别回头了 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:09

    Auth state change listener didn't work for me. Field isEmailVerified remains false even after user verifies his email.

    My workaround: Started from the assumption that user leaves the app to verify his email (which mean app is paused), and he returns to the app after verifying it (app resumes).

    What I did was attach a WidgetsBinding to a relevant stateful widget where I wanted to display if email was verified (but can be done elsewhere). This involves two steps.

    First step is to attach the binding:

      @override
      void initState() {
        WidgetsBinding.instance.addObserver(this);
        super.initState();
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    

    Second step is to override the didChangeAppLifecycleState to reload the user. I created a function that does the reload and sets a new firebaseUser object

      void didChangeAppLifecycleState(AppLifecycleState state) {
        if (state == AppLifecycleState.resumed && !firebaseUser.isEmailVerified)
          refreshFirebaseUser().then((value) => setState(() {}));
        super.didChangeAppLifecycleState(state);
      }
      Future refreshFirebaseUser() async {
        await firebaseUser.reload();
        firebaseUser = FirebaseAuth.instance.currentUser;
      }
    

    So what this is basically doing is to reload firebase user object everytime the user returns to the app, while its email is not verified. I chose this solution over setting and cancelling a timer as it avoided setting a recurrent action through a timer which could be overkill for this particular problem.

提交回复
热议问题