Flutter Firebase Authentication currentUser() returns null

一世执手 提交于 2021-02-09 11:10:42

问题


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()

回答1:


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.




回答2:


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();



回答3:


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.



来源:https://stackoverflow.com/questions/50439051/flutter-firebase-authentication-currentuser-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!