I keep getting this error The following _CastError was thrown building Builder: Null check operator used on a null value
on my view after using the following code, I do not understand how to get around it. When I check in if statement for the empty email then obviously the value wont be null, so I added an !
, why does it keep throwing this error?
Can someone give advice?
final TextEditingController _email = TextEditingController();
final TextEditingController _password = TextEditingController();
bool _isChecked = false;
@override
void initState() {
super.initState();
UserPreferences.init();
if (UserPreferences.getEmail != '') {
setState(() {
_isChecked = true;
_email.text = UserPreferences.getEmail!;
_password.text = UserPreferences.getPassword!;
});
}
}
class UserPreferences {
static SharedPreferences? _preferences;
static void init () async {
_preferences = await SharedPreferences.getInstance();
}
static setEmail(String username) async {
await _preferences?.setString('email', username);
}
static setPassword(String password) async {
await _preferences?.setString('password', password);
}
static String? get getEmail => _preferences?.getString('email');
static String? get getPassword => _preferences?.getString('password');
}
CodePudding user response:
Try this:
static Future<void> init () async {
_preferences = await SharedPreferences.getInstance();
}
And initState
should be like so:
@override
void initState() {
super.initState();
UserPreferences.init().then((_){
if (UserPreferences.getEmail != '') {
setState(() {
_isChecked = true;
_email.text = UserPreferences.getEmail!;
_password.text = UserPreferences.getPassword!;
});
}
});
}
CodePudding user response:
When I check in if statement for the empty email then obviously the value wont be null
This is a wrong assumption. null != ''
evaluates to true. Because in fact null is not an empty string