I'm using Flutter with firebase_auth plugin/s from Flutterfire. This is how the flow looks like in my app:
- Initialize Firebase.
- I use StreamBuilder to build "Landing Page" or "1st Page after logging in" depending on whether the user is logged in or not. Here's the relevant code:

When there is no user logged in, snapshot.data i.e. User returns null, hence the builder builds the "Landing Page".
3. The user taps on login button and a "Login Page" gets pushed on top of our "Landing Page". Here the user inputs a phone number and taps on "Verify phone number" button which triggers following code:
try {
await _auth.verifyPhoneNumber(
phoneNumber: _phone,
verificationCompleted: _verificationCompleted,
verificationFailed: _verificationFailed,
codeSent: _codeSent,
codeAutoRetrievalTimeout: _codeAutoRetrievalTimeout,
timeout: const Duration(seconds: 30),
);
} catch (e) {
print('Failed to verify phone number: $e');
}
Firebase starts to verify the phone number and sends an OTP to the phone via SMS. This triggers the codeSent void Callback from the above code, which causes the OTP TextField and a "Submit OTP" button to appear on the page.
3. User enters the OTP from SMS and taps "Submit OTP" button which triggers the following code:
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: _otpController.text.trim(),
);
await signInWithPhoneAuthCredential(phoneAuthCredential);
Future<void> signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) async {
UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(phoneAuthCredential);
// Code to take in some user details
// like address, topics to follow, etc.
// These details need to be taken from
// new users, because the "1st Page" depends
// on them.
return;
}
Now the problem is, whenever the method signInWithCredential(phoneAuthCredential) finishes executing, firebase signs the user in, and this method notifies its listeners about the auth state change including the Stream<User> authStateChanges() which we used in step 2 above. This causes the builder to pluck the landing page(and its descendants) out of the widget tree and replaces it with "FirstPage".
Due to this, everything below the signInWithCredentials call is not executed.
I observed on the Firebase console that the user does get logged in. But I'm not able to take details from the new users, first thing after signup.
I learned that the UserCredential userCredential object has a property that tells us if the user is freshly logged in. It is obtained using this code:
userCredential.additionalUserInfo.isNewUser
which return true if user is new. But I need to use it before the method signInWithCredentials notifies its listeners about the auth state change.
I couldn't possibly prompt the same user for entering the same details every time he/she logs in. Help me on this.