我已经在我的 flutter 应用程序上实现了 Firebase 电话身份验证。但是每当我发送调用 initAuth
方法时,我都会在我的控制台上收到 code sent
然后在 60 秒后 timed out
。我的理解只是来 self 的代码,但我希望收到短信或自动登录。似乎我从未调用过 verificationCompleted
方法。
下面是我的代码:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class PhoneVerification{
initAuth({BuildContext context, String phoneNumber}) async{
print(phoneNumber);
var firebaseAuth = FirebaseAuth.instance;
await firebaseAuth.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: Duration(seconds: 60),
codeSent:(String verificationId, [int forceResendingToken]){
print("Code Sent");
},
codeAutoRetrievalTimeout: (String verificationId){
print("Timed out");
},
verificationCompleted: (AuthCredential auth) async {
print("This User is authenticated by google play services");
firebaseAuth.signInWithCredential(auth)
.then((AuthResult result) =>{
if(result != null && result.user != null){
print("Authentication is Successful")
}else{
print("Authentication failed!")
}
})
.catchError((error){
print(error);
});
},
verificationFailed: (AuthException authException){
print('Error message: ' + authException.message);
},
);
}
}
这是我编写的用于调用 initAuth
方法的方法:
Future<void> sendSMS({context}) async{
User user = Provider.of<UserProvider>(context, listen: false).user;
PhoneVerification phoneVerification = PhoneVerification();
await phoneVerification.initAuth(context: context, phoneNumber: user.phone);
}
最后,我对组件中的按钮进行实际调用。下面是我如何调用 sendSMS
方法。
EnterPhone(onPress: ()=> sendSMS(context: context)),
最佳答案
对我来说:
// For firebase auth
final auth = FirebaseAuth.instance;
//
final PhoneVerificationCompleted verificationCompleted =
(AuthCredential phoneAuthCredential) async {
final res = await auth.signInWithCredential(phoneAuthCredential);
// Todo After Verification Complete
);
};
//
final PhoneVerificationFailed verificationFailed =
(AuthException authException) {
print('Auth Exception is ${authException.message}');
};
//
final PhoneCodeSent codeSent =
(String verificationId, [int forceResendingToken]) async {
print('verification id is $verificationId');
verId = verificationId;
};
//
final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
(String verificationId) {
verId = verificationId;
};
//
await auth.verifyPhoneNumber(
// mobile no. with country code
phoneNumber: '+91${_mobile.text}',
timeout: const Duration(seconds: 30),
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
关于Firebase 电话身份验证只是超时,不发送短信或自动登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63298827/