简体   繁体   English

电话认证 Firebase Flutter

[英]Phone Authentication Firebase Flutter

I have implemented the Phone Authentication in FLutter and its working.我已经在 FLutter 及其工作中实现了电话身份验证。 I just need to add a functionality.我只需要添加一个功能。

Check whether the user has entered the correct otp which is received on the entered phone number or not If the entered otp is incorrect error message should be displayed.检查用户是否输入了正确的 otp,如果输入的 otp 不正确,则应显示错误消息。

some code snippet:一些代码片段:

AuthService.dart AuthService.dart

class AuthService{
  handleAuth(){
    return StreamBuilder(
        stream: FirebaseAuth.instance.onAuthStateChanged,
        builder: (BuildContext context, snapshot){
          if(snapshot.hasData){
            return LoginSuccessScreen();
          }
          else{
            return SignInScreen();
          }
        }
    );
  }

  signOut(){
    FirebaseAuth.instance.signOut();
  }

  signIn(AuthCredential authCreds){
    FirebaseAuth.instance.signInWithCredential(authCreds);

  }

  signInWithOtp(context,smsCode,verId){
    AuthCredential authCreds = PhoneAuthProvider.getCredential(
        verificationId: verId,
        smsCode: smsCode
    );
    Navigator.pushReplacement(context,
        MaterialPageRoute(
            builder: (context) => LoginSuccessScreen()
        )
    );
    signIn(authCreds);

  }

SignIn.dart登录.dart

Future<void> verifyPhone(phoneNo) async {

    final PhoneVerificationCompleted verified = (AuthCredential authResult){
      print('sms1');
      AuthService().signIn(authResult);
    };

    final PhoneVerificationFailed verificationFailed = (AuthException authException){
      print('${authException.message}');
      verificationFailedErrorExist = true;
      setState(() {

      });

    };

    final PhoneCodeSent smsSent = (String verId, [int forceResend]){
      this.verificationId = verId;
      print('sms');
      Navigator.pushReplacement(context,
                    MaterialPageRoute(
                        builder: (context) => OtpScreen(verificationId)
                    )
                );
      

      setState(() {


      });
    };

    final PhoneCodeAutoRetrievalTimeout autoTimeOut = (String verId){
      this.verificationId = verId;
    };

    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: phoneNo,
        timeout: const Duration(seconds: 30),
        verificationCompleted: verified,
        verificationFailed: verificationFailed,
        codeSent: smsSent,
        codeAutoRetrievalTimeout: autoTimeOut
    );
  }

Otp.dart Otp.dart

Widget OtpForm() {
    return Form(
      child: Column(
        children: [
          SizedBox(height: SizeConfig.screenHeight * 0.15),
          PinCodeTextField(
            appContext: context,
            length: 6,
            onChanged: (value) {
              otp = value;
            },
            keyboardType: TextInputType.number,
            errorAnimationController: errorController,
            pinTheme: PinTheme(
              shape: PinCodeFieldShape.underline,
              inactiveColor: Colors.black38,
              activeColor: ErrorCode,
            ),

          ),

          SizedBox(height: SizeConfig.screenHeight * 0.15),
          DefaultButton(
            text: "Verify OTP",
            press: () {
              AuthService().signInWithOtp(context,otp, widget.verId);
              if (otp.length !=6 ) {
                errorController.add(ErrorAnimationType.shake);
                ErrorCode = Colors.red;
                setState(() {
                });
                print('nohellp');

              }
            },
          )
        ],
      ),
    );
  }
//otp send on button clicked
  Future otpSendOnMobile() async {
    final PhoneCodeSent smsOTPSent = (String verId, [int forceCodeResend]) {
      verify = verId;
      print('Code sent to ${codeCountry}${numberController.text}');
    };
    try {
      await FirebaseAuth.instance.verifyPhoneNumber(
          phoneNumber: "${codeCountry}${numberController.text}",
          codeAutoRetrievalTimeout: (String verId) {
            verify = verId;
          },
          codeSent: smsOTPSent,
          timeout: const Duration(seconds: 120),
          verificationCompleted: (AuthCredential phoneAuthCredential) {
            print(phoneAuthCredential);
          },
          verificationFailed: (exception) {
            print('${exception.message}');
          });
    } catch (e) {
      Exception(e);
    }
  }
  //Otp verification
  dynamic verifyOtpCode() async {
    try {
      final AuthCredential credential = PhoneAuthProvider.getCredential(
        verificationId: verify,
        smsCode: smsOTP,
      );
      await FirebaseAuth.instance
          .signInWithCredential(credential)
          .then((user) async {
        EasyLoading.dismiss();
      });
    } on PlatformException catch (e) {
      EasyLoading.dismiss();
      ToastUtils.showError(message: 'Enter correct OTP');
      print(e);
    }
  }

Here smsOtp is textfield controller value or your enter otp value.这里 smsOtp 是文本字段 controller 值或您输入的 otp 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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