我正在尝试通过使用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
...
})
答案 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');
};
我认为您不需要异步