Bhawna Saroha
Bhawna Saroha

Reputation: 633

FirebaseAuth: How to change phone number already linked to a provider?

I am working on a Flutter app which uses Firebase Authentication. I have used multiple providers and phone verification for the registration process.

I want to give an option to the user to change the phone number linked to their email ID. But for that, I need to verify the number again. And I'm having trouble doing that.

I am using unlinkFromProvider function and then linking it again using linkWithCredential. Here is the code for that.

FirebaseUser _firebaseUser = await _auth.currentUser();
var credential = PhoneAuthProvider.getCredential(
  smsCode: smsCode,
  verificationId: verificationId,
);
await _firebaseUser.unlinkFromProvider(_firebaseUser.providerId);
result = await _firebaseUser.linkWithCredential(credential);

But on doing this, I am getting this error

ERROR_NO_SUCH_PROVIDER: User was not linked to an account with the given provider.

I believe it means that the provider ID might be wrong.

How can I get the correct provider ID? Am I doing it completely wrong?

If yes, what is the right way to do this?

Thank you for your time!

Upvotes: 1

Views: 1983

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599131

You should not unlink the provider to re-verify the user's phone number. Instead you should reauthenticate the user with the reverification credentials.

After that, you can then call updatePhoneNumber to update the number.

Upvotes: 1

Peter Haddad
Peter Haddad

Reputation: 80924

You need to iterate inside the providerData list to get the correct providerId:

      FirebaseUser user = await FirebaseAuth.instance.currentUser();
      user.providerData.forEach((element) {
        element.providerId;
      });

_firebaseUser.providerId is most probably returning firebase, when you iterate inside the providerData, you will then get the providerid phone, and then you can unlink.

Upvotes: 1

Related Questions