3
votes

This is about Flutter Firebase Authentication plugin.
I am trying to send a verification email after creating a new user, but sendEmailVerification() internally uses currentUser(). This looks like a bug to me, but just in case, I am posting a question to stackoverflow. The error is the same on Android and IOS.

First two lines return FirebaseUser. The third returns null. Forth, if third is commented throws a null reference error.

Thanks,
Boris

user = await _auth.createUserWithEmailAndPassword(email: email, password: password); 
// result is FirebaseUser
user = await _auth.signInWithEmailAndPassword(email: email, password: password);
// result is FirebaseUser    
user = await _auth.currentUser();
// result is null    
await user.sendEmailVerification();
//null reference, because it internally uses .currentUser()
3

3 Answers

2
votes

Here is what I found, and I am no sure is it still a bug or not, but there is a way to make it work. FirebaseUser returned by signInWithEmailAndPassword is not really authenticated. Only user returned by onAuthStateChanged stream is. So, if you call user.sendEmailVerification() from onAuthStateChanged context, then everything is fine.

This will work:

_firebaseUserChanged = _auth.onAuthStateChanged.listen((FirebaseUser user) {
    if (user != null && !user.isEmailVerified) {
        user.sendEmailVerification(); 
   }
});

Of course, this code is simplified. We do not want to send verification email on every login attempt.

1
votes

Looking at the firebase_auth code I see that signInWithEmailAndPassword does instantiate and return a user. That's probably the user you need to call sendEmailVerification with.

final user = await _auth.signInWithEmailAndPassword(email: email, password: password);
await user.sendEmailVerification();
0
votes

What if you reload the returned FirebaseUser? This worked for me.

const User currentUser = await auth.currentUser;
if (currentUser != null) {
  await currentUser.reload();
}

Clearly simplified code. Note: auth.currentUser() is now auth.currentUser.