I have implemented the Firebase phone authentication on my flutter application. But anytime I send invoke the initAuth method, I get code sent on my console then after 60 secs timed out. That I understand is simply coming from my code but I expected an SMS or an auto login. It seems I don't ever get the verificationCompleted method invoked.
Below is my code:
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);
},
);
}
}
This is the method I wrote to invoke the initAuth method:
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);
}
Then finally, I am making the actual call onPress of a button in a component. Below is how I invoked the sendSMS method.
EnterPhone(onPress: ()=> sendSMS(context: context)),
for me :
// 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);
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