Home > database >  Flutter: Check if existing user or new user after OTP Authentication
Flutter: Check if existing user or new user after OTP Authentication

Time:05-04

I am trying to check after the OTP Process whether a user is a returning user that exists in my firebase or a new user and if so should be taken to a page where he inputs his details in it.

I have already made the user go to the chat screen after verifying OTP, but I want it to check first to see if the user is existing or not so that I get extra details before he continues to the chat screen.

This is the authentication function that I use.

  Future<void> phoneSignIn(
    BuildContext context,
    String phoneNumber,
  ) async {
    TextEditingController codeController = TextEditingController();
    try {
      // FOR ANDROID, IOS
      final newUser = await _auth.verifyPhoneNumber(
        phoneNumber: phoneNumber,
        timeout: const Duration(seconds: 120),
        //  Automatic handling of the SMS code
        verificationCompleted: (PhoneAuthCredential credential) async {
          // !!! works only on android !!!
          await _auth.signInWithCredential(credential);
        },
        // Displays a message when verification fails
        verificationFailed: (e) {
          showSnackBar(context, e.message!);
        },
        // Displays a dialog box when OTP is sent
        codeSent: ((String verificationId, int? resendToken) async {
          showOTPDialog(
            codeController: codeController,
            context: context,
            confirmOTP: () async {
              PhoneAuthCredential credential = PhoneAuthProvider.credential(
                verificationId: verificationId,
                smsCode: codeController.text.trim(),
              );
              

              // !!! Works only on Android, iOS !!!
              await _auth.signInWithCredential(credential);
              Navigator.of(context).pop(); // Remove the dialog box
            },
          );
        }),
        codeAutoRetrievalTimeout: (String verificationId) {
          // Auto-resolution timed out...
        },
      );
    } catch (e) {
      print(e);
    }
  }

and this is the OTP simple dialog to input the OTP code received


void showOTPDialog({
  required BuildContext context,
  required TextEditingController codeController,
  required VoidCallback confirmOTP,
}) {
  showDialog(
    context:context,
    barrierDismissible: false,
    builder: (context)=> AlertDialog(
      title: const Text("Enter OTP"),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children:<Widget>[
          TextField(
            controller: codeController,
          )
        ]
      ),
      actions: <Widget>[
        TextButton(
          child:const Text('Confirm Code'),
          onPressed: confirmOTP,
        )
      ],
    ),

  );
}```

CodePudding user response:

This is how you can do

auth.verifyPhoneNumber(
    phoneNumber: phoneNumber,
    verificationCompleted: (PhoneAuthCredential credential) async {
      final userCredential = await auth.signInWithCredential(credential);
      final isNew = userCredential.additionalUserInfo?.isNewUser ?? false;
      print('isNew $isNew'); // This is where you will get the value
    },
    verificationFailed: (FirebaseAuthException e) {},
    codeSent: onOtpSentHandler,
    codeAutoRetrievalTimeout: (String verificationId) {},
  );
  • Related