How to link phone number to already logged in email user which is using firebase

Viewed 37

I want to link the already login user who has login from their email id when starting the website but after completing the signup process I want to add the phone number of the user but I am getting an error as firebase creates a new id every time when creating a new id after the phone OTP verification.

So, after some digging, I found out that there is a way to LINK already logged in the user with an email with a phone number.

But, the function is not working for me

here is my code for adding a phone number and then linking it with current user credentials.

sendOTP(String phoneNumber) async {
this.phoneNumber = phoneNumber;
FirebaseAuth auth = FirebaseAuth.instance;
print('${phoneCode}');
ConfirmationResult confirmationResult =
    await auth.signInWithPhoneNumber('+${phoneCode}${phoneNumber}');
if (kDebugMode) {
  print("OTP send to +${phoneCode} ${phoneNumber}");
}
return confirmationResult;
   }



 authenticateMe(ConfirmationResult confirmationResult, String otp) async {
    UserCredential userCredential = await confirmationResult.confirm(otp);

    signIn(AuthCredential userCredential) async {
      //now link these credentials with the existing user
      UserCredential? linkauthresult =
          await existingUser?.linkWithCredential(userCredential);
      print('linked');
    }

    firebaseOtp = otp;

    
  }

here is my User existingUser = FirebaseAuth.instance.currentUser!; variable which is i am calling in init state

 @override


void initState() {
    super.initState();
    existingUser;
    print('this is current user from otp_container  ${existingUser}');
  }

and here is my button onPressed function

onPressed: () {
    authenticateMe(
      temp,
      otpCodeController.text,
    );
    Future.delayed(const Duration(seconds: 3))
        .then((value) {
      if (!mounted) {
        const CircularProgressIndicator();
      }
      setState(() {
        if (otpCodeController.text ==
            firebaseOtp) {
          isAnimatedContainer =
              !isAnimatedContainer;
          
        } else {
          setState(() {
            verifyOtpcheck = !verifyOtpcheck;
          });
        }
      });
    });
  },

and I am working on flutter web.

0 Answers
Related