0
votes

I have implemented the Phone Authentication in FLutter and its working. 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.

some code snippet:

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

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

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');

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

1 Answers

0
votes
//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 .