首页 > 解决方案 > 如何在flutter中自动从firebase SMS中读取OTP

问题描述

我正在编写一个代码,该代码要求提供 OTP 验证码以在 firebase 中注册手机。它手动工作正常,但我想让代码或应用程序读取从 firebase 以 SMS 发送的代码并自动检查。例如,大多数应用在请求验证码时,手机收到验证码后,会自动将验证码写入验证码注册框。

我搜索了很长时间,但它对我不起作用。

完整代码:



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


标签: flutterfirebase-authentication

解决方案


对于 IOS,默认提供 SMS 自动填充。

对于 android 你可以使用这个包


推荐阅读