In my flutter app I am using firebase phone authentication for login purpose. in all way, its working perfectly. By using my current code I have to add sms code explicitly when I receive the code.
How can I make this sms verification automatically in my flutter app?
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);
}
In onPhoneVerificationCompleted Write this:
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);
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With