Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reading OTP from firebase SMS automatically in flutter

I'm working on a code that asks for an OTP verification code to register the phone in firebase. It works fine manually but I want to make the code or app read the code sent in SMS from firebase and check it automatically. For example, most applications when the verification code is requested and after the phone receives the verification code, the code is automatically written in the verification code registration boxes.

I searched for a long time, but it didn't work with me.

full code:



class _OtpScreenState extends State<OtpScreen> {
  String phoneNo;
  String smsOTP;
  String verificationId;
  String errorMessage = '';
  final FirebaseAuth _auth = FirebaseAuth.instance;
  bool showLoading = false;
  void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) async {
    setState(() {
      showLoading = true;
    });

    try {
      final authCredential = await _auth.signInWithCredential(phoneAuthCredential);

      setState(() {
        showLoading = false;
      });

      if (authCredential?.user != null) {


      }
    } on FirebaseAuthException catch (e) {
      setState(() {
        showLoading = false;
      });
      print(e.message);
    }
  }


  @override
  Widget build(BuildContext context) {

    return    MaterialApp(
      home: Scaffold(
        body: Center(
          child: SingleChildScrollView(
            child: Container(
              child: Column(

                children: [


                  Container(

                    padding: const EdgeInsets.all(16.0),

                    child: Column(

                      children: [

                        Row(
                          children: [
                            Expanded(
                              child: PinEntryTextField(

                                fields: 6,
                                onSubmit: (text) {
                                  smsOTP = text as String;
                                },
                              ),
                            ),
                          ],
                        ),

                        GestureDetector(
                          onTap: () {
                            verifyOtp();
                          },
                          child: Container(
                            margin: const EdgeInsets.all(8),
                            height: 45,
                            width: double.infinity,
                            decoration: BoxDecoration(
                              color:     CustomColors.Background,
                              borderRadius: BorderRadius.circular(0),
                            ),
                            alignment: Alignment.center,
                            child:  Text('Check'),

                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }


  Future<void> generateOtp(String contact) async {
    final PhoneCodeSent smsOTPSent = (String verId, [int forceCodeResend]) {
      verificationId = verId;
    };
    try {
      await _auth.verifyPhoneNumber(
          phoneNumber: contact,
          codeAutoRetrievalTimeout: (String verId) {
            verificationId = verId;
          },
          codeSent: smsOTPSent,
          timeout: const Duration(seconds: 60),
          verificationCompleted: (AuthCredential phoneAuthCredential) {},
          verificationFailed: (exception) {
            print(exception);

          });
    } catch (e) {
      handleError(e as PlatformException);

    }
  }

  //Method for verify otp entered by user
  Future<void> verifyOtp() async {
    if (smsOTP == null || smsOTP == '') {
      print('please enter 6 digit otp');
      return;
    }
    try {

      final AuthCredential credential = PhoneAuthProvider.credential(
        verificationId: verificationId,
        smsCode: smsOTP,
      );
      signInWithPhoneAuthCredential(credential);

    } catch (e) {
      handleError(e as PlatformException);
    } }

  void handleError(PlatformException error) {
    switch (error.code) {
      case 'ERROR_INVALID_VERIFICATION_CODE':
        FocusScope.of(context).requestFocus(FocusNode());
        setState(() {
          errorMessage = 'Invalid Code';
        });
        print('error');
        break;
      default:
        print('error');
        break;
    }
  }
}


like image 748
M Al Avatar asked Oct 21 '25 19:10

M Al


2 Answers

For IOS, SMS autofill is provided by default.

For android you can use this package.

like image 147
Rudra Gupta Avatar answered Oct 23 '25 08:10

Rudra Gupta


Use this in your code:

String otpValue = credential.smsCode.toString();

Example from my code:

enter image description here

like image 38
Sonu kumar Avatar answered Oct 23 '25 08:10

Sonu kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!