Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onAuthStateChanged doesn't get called when email is verified in flutter

When a user signs up in my app he gets a verification e-mail. The onAuthStateChanged-listener gets called when a user gets created using createUserWithEmailAndPassword but not after the email got verified.

I have a separate class which handles all authentications. The following method is to sign up user

Future<FirebaseUser> signUpUser(email, password) async {
final FirebaseUser user = await _auth.createUserWithEmailAndPassword(email: email, password: password);

assert (user != null);
assert (await user.getIdToken() != null);

return user;
}

This method is called in my StatefulWidget using this method

void _signUpUser() async {
try {
  await Auth().signUpUser(_email, _password)
    ..sendEmailVerification();
} catch (e) {
  print(e.toString());
}
}

And onAuthStateChanged is set up in the initState method of my StatefulWidget

  FirebaseAuth.instance.onAuthStateChanged.listen((user) {
  print("Auth State Changed!");
  if (user.isEmailVerified) {
    print("EMail verified!");
  }
  }
like image 813
eli2003 Avatar asked Feb 08 '19 11:02

eli2003


3 Answers

onAuthStatechanged is triggered only in case of user Login or Logout & not on Email verification.

As Per Doc -

onAuthStatechanged Adds an observer for changes to the user's sign-in state.

The observer will be triggered in the following scenarios:

  • When auth().onAuthStateChanged() is first called. It will trigger with the initial Auth state. If the user is returning from an auth().signInWithRedirect() operation, the observer will wait for that operation to resolve before initially triggering.

  • When a new user signs.

  • When an already signed in user signs out.

like image 194
anmol.majhail Avatar answered Oct 19 '22 13:10

anmol.majhail


At the moment I'm providing a button to 'complete email validation'. This calls User.reload - so this appears to be enough per @Frank van Puffelen's comment above. It's much less satisfactory than getting a status update event; I may implement a loop to check the status for a period after sending an email so that the app passes through automatically.

like image 37
Richard K Avatar answered Oct 19 '22 13:10

Richard K


You can simply do a firebase.auth().signOut after sending the email verification link. And when the user clicks on sign in again, it'll automatically fire onAuthStateChanged.

like image 1
Sahil Tyagi Avatar answered Oct 19 '22 13:10

Sahil Tyagi