在Flutter中重新发送OTP代码Firebase电话身份验证

时间:2020-04-10 00:14:32

标签: flutter dart firebase-authentication

这可能是重复的,但是其他任何线程都没有为我提供正确的答案。

有关于android本地语言的答案,但没有关于Flutter(dart)的答案。

我有以下可行的方法,但是如果我想向用户电话号码重新发送OTP,我该怎么做?只是一个简单的示例代码可能会有所帮助。

  Future signInWithPhone(String phone, BuildContext context) async {

    // This triggers if verification passes
    final PhoneVerificationCompleted verificationCompleted = (AuthCredential credential) async {
      Navigator.of(context).pop();

      AuthResult result = await _auth.signInWithCredential(credential);

      FirebaseUser user = result.user;

      if(user != null){
        Navigator.push(context, MaterialPageRoute(
          builder: (context) => HomeScreen(user: user,)
        ));
      }else{
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Alert Dialog"),
              content: Text('Error'),
            );
          }
        );
      }
    };

    // This triggers if verification fails
    PhoneVerificationFailed verificationFailed = (AuthException exception) {
      toast(exception.message, 'long');
    };

    // This is to send code to the user But i dont know how to resend
    final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) {
        var route = MaterialPageRoute(
          builder: (BuildContext context) => LoginPhoneVerify(verificationId, phone)
        );

        Navigator.of(context).push(route);
    };

    // The main function
    await _auth.verifyPhoneNumber(
      phoneNumber: phone,
      timeout: Duration(seconds: 0),
      verificationCompleted: verificationCompleted,
      verificationFailed: verificationFailed,        
      codeSent: codeSent,
      codeAutoRetrievalTimeout: null
    );


  }

我在以下线程中找到了适用于android的内容:

https://stackoverflow.com/a/44688838/10114772

private void resendVerificationCode(String phoneNumber, PhoneAuthProvider.ForceResendingToken token) {
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks,         // OnVerificationStateChangedCallbacks
            token);             // ForceResendingToken from callbacks
}

但是那不是为了扑朔迷离,请有人看看!

3 个答案:

答案 0 :(得分:1)

因此,按照我的说明浏览完文档后,回想起

verifyPhoneNumber()

方法将重新发送OTP代码。

答案 1 :(得分:1)

第一次发送otp时,从codeSent回调中记录forceResendingToken的值作为resendToken,然后再次发送otp,然后在auth.verifyPhoneNumber()函数中添加一个额外的参数forceResendingToken:resendToken。

答案 2 :(得分:0)

我遇到了同样的问题,我只是禁用重发按钮直到超时并显示相同持续时间的倒数计时器,超时后您可以启用重发按钮,用户可以重新发送代码。它对我有用。