Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 address. Therefor I push the Firebase users after registration to a verification screen. This is just a loading screen which tells the user that he has to verify his email.

But now: How can I continuously listen, if the users email is verified or not and send him (when true) to the Homescreen?

I'm new to Flutter and I don't know if I have to use a Streams or Observables or a while Loop or setState() or something else for such a boolean check. And I also don't know how to setup a solution.

This is my basic code for register a user:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final Firestore _db = Firestore.instance;

  Future<FirebaseUser> get getUser => _auth.currentUser();

  Stream<FirebaseUser> get user => _auth.onAuthStateChanged;

  Future<FirebaseUser> edubslogin(String email, String password) async {
    try {
      final FirebaseUser user = await _auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
     
      await user.sendEmailVerification();
      
      //email verification somewhere here
    
      updateUserData(user);
      return user;
    } catch (error) {
      print(error);
      return null;
    }
  }

I've tried this:

     if (user.isEmailVerified == true) {
        
        //go to Homescreen
        return true; 
      } else {

        //show verification screen(loading spinner)
        return false;
      }

But I don't get a boolean value true out of isEmailVerified.

What do I have to do?

like image 805
eifachtimon Avatar asked Jul 25 '19 00:07

eifachtimon


Video Answer


3 Answers

I faced the same situation in my app. My solution was to create a periodic timer into the initState method of a strategic route to hold the app until the e-mail is verified. It is not so elegant as using a listener but works fine.

import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';

class _AccountConfirmationState extends State<AccountConfirmation> {

    late Timer _timer;

    @override
    void initState() {
      super.initState();
      
      _timer = Timer.periodic(const Duration(seconds: 5), (timer) async {
      await FirebaseAuth.instance.currentUser?.reload();
      final user = FirebaseAuth.instance.currentUser;
        if (user?.emailVerified ?? false) {
          timer.cancel();
          Navigator.pop(context, true);
        }
      });
    }

    @override
    void dispose() {
      super.dispose();
      _timer.cancel();
    }

    @override
    Widget build(BuildContext context) {
      //TODO: Implement your amazing waiting screen here
    }

}
like image 152
Alisson Oliveira Avatar answered Sep 29 '22 18:09

Alisson Oliveira


This verification isn't as straightforward as you'd hope. First, there is the problem of recognizing that the user has verified their email. Second, there is the issue that there isn't any sort of a notification you can listen to that will automatically trigger a change in your app.

Check this thread for info about emailVerified: https://github.com/flutter/flutter/issues/20390#issuecomment-514411392

I was only able to verify the user if I 1) Created their account, 2) Signed them in, 3) Then checked to make sure they verified their email.

final FirebaseAuth _auth = FirebaseAuth.instance;

var _authenticatedUser = await _auth.signInWithEmailAndPassword(email: _email, password: _password); 

//where _email and _password were simply what the user typed in the textfields.



if (_authenticatedUser.isEmailVerified) {
        //Verified
      } else {
        //Not verified
        }

Part 2: How do you get your app to recognize that the user has confirmed their email? Find a way to trigger the function that checks confirmation. A button would be easy enough. If you want it to see "automatic" then I guess you could create a timer that checks for email verification every 10 seconds or so.

like image 11
Eric Duffett Avatar answered Sep 30 '22 18:09

Eric Duffett


Well I created a stream to handle this. Not so elegant but works. Use a StreamProvider.value() to handle events.

  Stream<userVerificationStatus> checkUserVerified() async* {
    bool verified = false;
    yield userVerificationStatus(status: Status.LOADING); 
    while (!verified) {
      await Future.delayed(Duration(seconds: 5));
      FirebaseUser user = await _auth.currentUser();
      if(user!=null)await user.reload();
      if (user == null) {
        yield userVerificationStatus(status: Status.NULL);
      } else {
        print("isemailverified ${user.isEmailVerified}");
        await user.reload();
        verified = user.isEmailVerified;
        if(verified)
        yield userVerificationStatus(status: Status.VERIFIED);
        else
        yield userVerificationStatus(status: Status.NOT_VERIFIED);
      }
    }
  }
like image 2
TheAnimatrix Avatar answered Sep 30 '22 18:09

TheAnimatrix