颤振电话号码身份验证为null验证ID?

时间:2020-08-02 10:35:43

标签: firebase flutter firebase-authentication

我正在尝试通过使用Firebase身份验证向我的电话设备发送短信代码来进行电话号码登录。但是await关键字在这里似乎不起作用。为什么?我的假设是当我将await分配给一个函数时,Flutter打印verificationId变量的空值,verificationId在_sendCodeToPhoneNumber函数中获取其值。因此,这可能意味着函数_sendCodeToPhoneNumber尚未完成,但是其下一行代码(在这种情况下为print(verificationId))已经执行。但是如果我弄错了,那是什么问题呢?更重要的是,请教我如何解决问题?因为我必须获取verificationId的值并将其传递给下一个类。

String verificationId;

Future<void> _sendCodeToPhoneNumber() async {
    ...

    final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) async {
      this.verificationId = verificationId; //this.verificationId here is not null because it has got a value
      print('Code sent to ${_phoneNumberController.text} with $verificationId');
    };

    ...
    await FirebaseAuth.instance.verifyPhoneNumber(
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
      phoneNumber: _phoneNumberController.text,
      codeSent: codeSent,
      timeout: const Duration(seconds: 120),
      verificationCompleted: verificationCompleted,
      verificationFailed: vericationFailed
    );
  }

...

FlatButton(onPressed: (){
 await _sendCodeToPhoneNumber();
 print(verificationId); // printed null despite having assigned `await` to the _sendCodeToPhoneNumber function
 ...
})

2 个答案:

答案 0 :(得分:0)

将函数更改为以下内容,然后返回verificationId

  Future<String> _sendCodeToPhoneNumber() async {
    final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) async {
      this.verificationId = verificationId; //this.verificationId here is not null because it has got a value
      print('Code sent to ${_phoneNumberController.text} with $verificationId');
    };
    await FirebaseAuth.instance.verifyPhoneNumber(
      codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
      phoneNumber: _phoneNumberController.text,
      codeSent: codeSent,
      timeout: const Duration(seconds: 120),
      verificationCompleted: verificationCompleted,
      verificationFailed: vericationFailed
    );
    return this.verificationId;
  }

还更改onPressed,使用await时需要使用async

FlatButton(onPressed: (()async{
 var result = await _sendCodeToPhoneNumber();
 print(result);
}))

答案 1 :(得分:0)

final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) async {
  this.verificationId = verificationId; //this.verificationId here is not null because it has got a value
  print('Code sent to ${_phoneNumberController.text} with $verificationId');
};

我认为您不需要异步