I am receiving following exception when using a FutureBuilder to build itself using a future "firebaseAuthSvc.signinwithphoneno(widget.pin, widget.verificationID)" that return Firebase Authentication UserCredential.
════════ Exception caught by widgets library ═══════════════════════════════════ The following _CastError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#a7b44): Null check operator used on a null value
The relevant error-causing widget was FutureBuilder lib/screens/enterpinsubwidgetsecondscreen.dart:34 When the exception was thrown, this was the stack #0 UserInfo.uid package:firebase_auth_platform_interface/src/user_info.dart:52 #1 UserInfo.toString package:firebase_auth_platform_interface/src/user_info.dart:57 #2 StringBuffer.write (dart:core-patch/string_buffer_patch.dart:64:22) #3 StringBuffer.writeAll (dart:core-patch/string_buffer_patch.dart:102:7) #4 IterableBase.iterableToFullString (dart:collection/iterable.dart:267:14)
My stateful widget using the future builder is as below.
class _EnterPinSubWidgetSecondScreenState
extends State<EnterPinSubWidgetSecondScreen> {
FirebaseAuthSvc firebaseAuthSvc = new FirebaseAuthSvc();
Future<UserCredential> _usercredential ;
@override
@override
void initState() {
super.initState();
print("Pin:${widget.pin} VerificationID: ${widget.verificationID}");
_usercredential =
firebaseAuthSvc.signinwithphoneno(widget.pin, widget.verificationID);
}
@override
Widget build(BuildContext context) {
print("Buildcontext of EnterPinSubWidgetSecondScreen");
return FutureBuilder<UserCredential>(
future: _usercredential,
builder: (context, snapshot) {
print(
"in EnterPinSubWidgetSecondScreen builder ${snapshot.connectionState} data= ${snapshot.data}");
if (snapshot.hasError) {
print("Some error in snapshot ${snapshot.error}");
return EnterPin();
}
if (snapshot.connectionState == ConnectionState.done) {
return EnterPinSubWidgetThirdScreen();
}
return LoadingScr("Signining in...");
},
);
}
}
My future using firebase phone authentication signinwithcredential is defined as
Future<UserCredential> signinwithphoneno(
String pin, String verificationID) async {
String smsCode = pin;
FirebaseAuth auth = FirebaseAuth.instance;
// Create a PhoneAuthCredential with the code
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(
verificationId: verificationID, smsCode: smsCode);
// Sign the user in (or link) with the credential
return auth.signInWithCredential(phoneAuthCredential).then((user) {
print("User not null ${user.user.phoneNumber}");
return user;
}).onError((error, stackTrace) {
print("signingwithcredential returned error $error");
return null;
});
}