我搜索了许多网站,但没有找到使用Firebase在Flutter中实现电话身份验证的方法。谁能告诉我该怎么做?
记录良好的工作演示项目在这里
下面是详细步骤
AuthCrendential
AuthCredential
verificationCompleted
verifyPhoneNumber
PhoneAuthProvider
(不要担心它是否令人困惑,请继续阅读,您会明白的)
phoneNumber
submitPhoneNumber
Future<void> _submitPhoneNumber() async { /// NOTE: Either append your phone number country code or add in the code itself /// Since I'm in India we use "+91 " as prefix `phoneNumber` String phoneNumber = "+91 " + _phoneNumberController.text.toString().trim(); print(phoneNumber); /// The below functions are the callbacks, separated so as to make code more readable void verificationCompleted(AuthCredential phoneAuthCredential) { print('verificationCompleted'); ... this._phoneAuthCredential = phoneAuthCredential; print(phoneAuthCredential); } void verificationFailed(AuthException error) { ... print(error); } void codeSent(String verificationId, [int code]) { ... print('codeSent'); } void codeAutoRetrievalTimeout(String verificationId) { ... print('codeAutoRetrievalTimeout'); } await FirebaseAuth.instance.verifyPhoneNumber( /// Make sure to prefix with your country code phoneNumber: phoneNumber, /// `seconds` didn't work. The underlying implementation code only reads in `milliseconds` timeout: Duration(milliseconds: 10000), /// If the SIM (with phoneNumber) is in the current device this function is called. /// This function gives `AuthCredential`. Moreover `login` function can be called from this callback verificationCompleted: verificationCompleted, /// Called when the verification is failed verificationFailed: verificationFailed, /// This is called after the OTP is sent. Gives a `verificationId` and `code` codeSent: codeSent, /// After automatic code retrival `tmeout` this function is called codeAutoRetrievalTimeout: codeAutoRetrievalTimeout, ); // All the callbacks are above }
void _submitOTP() { /// get the `smsCode` from the user String smsCode = _otpController.text.toString().trim(); /// when used different phoneNumber other than the current (running) device /// we need to use OTP to get `phoneAuthCredential` which is inturn used to signIn/login this._phoneAuthCredential = PhoneAuthProvider.getCredential( verificationId: this._verificationId, smsCode: smsCode); _login(); }
Future<void> _login() async { /// This method is used to login the user /// `AuthCredential`(`_phoneAuthCredential`) is needed for the signIn method /// After the signIn method from `AuthResult` we can get `FirebaserUser`(`_firebaseUser`) try { await FirebaseAuth.instance .signInWithCredential(this._phoneAuthCredential) .then((AuthResult authRes) { _firebaseUser = authRes.user; print(_firebaseUser.toString()); }); ... } catch (e) { ... print(e.toString()); } }
Future<void> _logout() async { /// Method to Logout the `FirebaseUser` (`_firebaseUser`) try { // signout code await FirebaseAuth.instance.signOut(); _firebaseUser = null; ... } catch (e) { ... print(e.toString()); } }
有关实现的更多详细信息,请参考此处的lib/main.dart文件。
lib/main.dart
如果发现问题,欢迎对此答案和此自述文件进行编辑