Ashutosh Singh
Ashutosh Singh

Reputation: 1277

Listening to changes in firebase auth credentials

I was building an app which requires me to sign in the user with two compulsory methods, the email as well as the phone number as both the type of data is crucial for the proper functioning of the app. I have implemented Firebase email-password based authentication and google sign in into my app along with phone verification.

Now, I have successfully implemented both the methods and managed to link the credentials of phone auth with email and the same is visible on the firebase console but the problem is that I'm not notified of any changes in auth credentials.

Here's the code I've used to determine which page to show depending on the state of snapshot.data

return StreamBuilder<FirebaseUser>(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting ||
            snapshot.connectionState == ConnectionState.none) {
          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        } else {
          if (snapshot.hasError) {
            return Scaffold(
              body: Center(
                child: Text("Error signing in. Please try later"),
              ),
            );
          } else if (snapshot.hasData) {
            print("signInHandler.dart phone: ${snapshot.data.phoneNumber}");
            if (snapshot.data.phoneNumber == null) {
              return PhoneSignIn();
            }
            return MyHomePage();
          }
          return EmailSignIn();
        }
      },
    );

Now I know as per documentaions, onAuthStateChanged is fired only if there was any sign in or sign out event but is there any way to know that the AuthCredentials have changed so that I can decide the appropriate page to show depending on the data?

However, when I hot reload the app after linking auth credentials, the appropriate screen is displayed i.e MyHomePage(). Before that, the app keeps displaying only the PhoneSignIn() screen ever after successfully linking the credentials.

Getting phone number using google's contacts API did not solve my problem as there are some google accounts which are not associated with any phone number.

I'd be very grateful if someone could point me in the right direction.

Upvotes: 0

Views: 1195

Answers (2)

Chukwuma Nwaugha
Chukwuma Nwaugha

Reputation: 715

singh, you'll need to force refresh the user idToken, getIdToken(true), so as propagate the new values for credentials, claims or providers on the auth user instance. You can read here for more.

Upvotes: 1

Ashutosh Singh
Ashutosh Singh

Reputation: 1277

In the end, I could not find any out of the box solution for the problem and had to use a bunch of streams and Bloc for managing this state.

Upvotes: 0

Related Questions