简体   繁体   中英

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;
    }
  }
}


For IOS, SMS autofill is provided by default.

For android you can use this package .

I don't know who Voted Down But It is correct one! Use this in your code;

String otpValue = credential.smsCode.toString();

Example From My Code

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM