gpt4 book ai didi

flutter - 如何使用 firebase_auth(电话身份验证)在 Flutter 应用程序中添加短信自动验证?

转载 作者:行者123 更新时间:2023-12-03 02:47:35 40 4
gpt4 key购买 nike

在我的 flutter 应用程序中,我使用 Firebase 电话身份验证进行登录。总而言之,它完美地工作。通过使用我当前的代码,我必须在收到代码时明确添加短信代码。

如何在我的 Flutter 应用程序中自动进行此短信验证?

    Future<void> _sendCodeToPhoneNumber() async {

final String phone = country + phoneNumberController.text;

final PhoneVerificationCompleted verificationCompleted =
(AuthCredential credential) {
setState(() {
print(
'Inside _sendCodeToPhoneNumber: signInWithPhoneNumber auto succeeded: $credential');
});
};

final PhoneVerificationFailed verificationFailed =
(AuthException authException) {
setState(() {
print(
'Phone number verification failed. Code: ${authException.code}. Message: ${authException.message}');
});
};

final PhoneCodeSent codeSent =
(String verificationId, [int forceResendingToken]) async {
this._verificationId = verificationId;
print("code sent to " + phone);
setState(() {
this.status = AuthStatus.SMS_AUTH;
});
};

final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
(String verificationId) {
this._verificationId = verificationId;

print("time out");
};

await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phone,
timeout: const Duration(seconds: 1),
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
}

最佳答案

在 onPhoneVerificationCompleted 中这样写:

final PhoneVerificationCompleted phoneVerificationCompleted =
(AuthCredential phoneAuthCredential) async {
print('Received phone auth credential: $phoneAuthCredential');
await _auth
.signInWithCredential(phoneAuthCredential)
.then((AuthResult result) {
// signin is successful
FirebaseUser firebaseUser = result.user;
// check if user exists already
getUserDetailsById(firebaseUser.uid).then((value) async {
if (value == null) {
// new user sign in
addDataToFirestore(firebaseUser).then((value) => {
// new user data added to db
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Home(),
),
);
});
} else {
// user already signed in
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Home(),
),
);
}
});
}).catchError((e) {
print(e);
});
};

关于flutter - 如何使用 firebase_auth(电话身份验证)在 Flutter 应用程序中添加短信自动验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57408405/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com