I'm trying to authenticate user with phone and as I'm using flutter_bloc and Repository the approach I'm having is:
- Send event with phone number to Bloc(OK).
- Call
verifyPhoneNumberpassing in the phone number (OK). - Return the
verificationIdreceived from eithercodeAutoRetrievalTimeoutorcodeSentcallbacks. - Send it to UI from
BlocListenerwith a State. - Update UI to enter the verification code.
- Send smsCode and verificationId to another method to link phone AuthCredential to user.
My method returns before callbacks are called as verifyPhoneNumber completes first so it's returning a null String.
What I'm doing wrong? As always many thanks for your help.
Future<String> verifyPhoneNumber(String phoneNumber) async {
print('verifyPhoneNumber() started');
String verifyId;
await _firebaseAuth
.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: Duration(minutes: 0),
//error: Undefined class 'PhoneAuthCredential'.
// verificationCompleted: (PhoneAuthCredential credential) async {
verificationCompleted: (AuthCredential credential) {
},
//error: Undefined class 'FirebaseAuthException'.
// verificationFailed: (FirebaseAuthException e) {
verificationFailed: (AuthException e) {
if (e.code == 'invalid-phone-number') {
print(
'verifyPhoneNumber() -> verificationFailed -> The provided phone number is not valid.');
} else {
print(
'verifyPhoneNumber() -> verificationFailed :${e.message}');
}
// Handle other errors
},
codeAutoRetrievalTimeout: (String verificationId) {
// Auto-resolution timed out...
// verifyId = verificationId;
print(
'verifyPhoneNumber() -> codeAutoRetrievalTimeout callback called');
},
//error: The argument type 'Null Function(String, int)' can't be assigned to the parameter type 'void Function(String, [int])'.
// codeSent: (String verificationId, int resendToken) {
codeSent: (String verificationId, [int resendToken]) {
verifyId = verificationId;
print(
'verifyPhoneNumber() -> codeSent callback called : $verifyId'); // correct
return verifyId;
}
)
.then((value) {
print('verifyId is $verifyId'); // null
// return verifyId;
}).whenComplete(() => print('Complete'));
print('verifyPhoneNumber() ->returning verifyId: $verifyId');
return verifyId; // without it method doesn't return, with it returns null
}