So, everything was going well when login but a _CastError
was thrown when logout even tho the logout was going fine but I am concerned about this error making a problem in production mode.
this is the code from my auth_model
Rxn<User> _user = Rxn<User>() ;
String? get user => _user.value!.email;
@override
void onInit() {
// TODO: implement onInit
super.onInit();
_user.bindStream(_auth.authStateChanges());
}
and this is the code from my controller_view
return Obx((){
return(Get.find<AuthViewModel>().user != null)
? HomeScreen()
: Home();
});
and this one is from my homeScreen
class HomeScreen extends StatelessWidget {
FirebaseAuth _auth = FirebaseAuth.instance;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Home Screen",
textAlign: TextAlign.center,
),
),
body: Column(
children: <Widget>[
Center(
child: TextButton(
child: Text(
"logout"
),
onPressed: () {
_auth.signOut();
Get.offAll(Home());
},
),
),
],
),
);
}
}
I'll appreciate any kind of help.
This is the problem.
/// You tried to declare a private variable that might be `null`.
/// All `Rxn` will be null by default.
Rxn<User> _user = Rxn<User>();
/// You wanted to get a String from `email` property... from that variable.
/// But you also want to return `null` if it doesn't exist. see: `String?` at the beginning.
/// But you also tell dart that it never be null. see: `_user.value!`.
String? get user => _user.value!.email;
/// That line above will convert to this.
String? get user => null!.email;
You are marking a null
as not-null
by adding a !
before the next operand. That is why you get the error. To fix that, use ?
instead of !
.
/// This will return `null` and ignore the next `.email` operand
/// if `_user.value` is `null`.
String? get user => _user.value?.email;