Null check operator used on a null value when checking with if
456
Generally speaking, using a !
in null checks means your code has bugs. If it didn't have bugs, you would not need this operator.
The !
operator only forces your compiler to go through with what you programmed, even though it knows it could be wrong. It warned you, but you decided that instead of listening to your compiler, you just told it to shut up (by using operator !
). If you want to write good code, just forget the operator !
for null checks ever existed.
final previousEmail = UserPreferences.getEmail;
final previousPassword = UserPreferences.getPassword;
if (previousEmail != null) {
setState(() {
_isChecked = true;
_email.text = previousEmail;
if(previousPassword != null) {
_password.text = previousPassword;
}
});
}
Author by
squnk
Updated on January 04, 2023Comments
-
squnk over 1 year
Whenever I go on my login page, I get the error that I used null check operator on a null value, it only happens when there is no login/password entered before. In init state I am checking with
isNotEmpty
, so why am I getting this error? How can I fix it?[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
@override void initState() { super.initState(); UserPreferences.init().then((_) { if (UserPreferences.getEmail!.isNotEmpty) { setState(() { _isChecked = true; _email.text = UserPreferences.getEmail!; _password.text = UserPreferences.getPassword!; }); } }); }
class UserPreferences { static SharedPreferences? _preferences; static Future<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'); }
-
Wilson Toribio about 2 yearsThis approach is not recommended since share preferences package does not encrypt the data. But what I recommend you is to initialize the _prefs.setString('email', '0') with some value for it not to be null when initializing.
-
squnk about 2 years@WilsonToribio then in my email input I will have '0' which I do not want
-
jamesdlin about 2 years
if (UserPreferences.getEmail!.isNotEmpty) {
asserts thatUserPreferences.getEmail
is notnull
(which might not necessarily be true) before calling theisNotEmpty
getter. Furthermore,isNotEmpty
has nothing to do with checking fornull
.
-
-
squnk about 2 yearsThanks, this null check operator has caused many errors in my app. I'll just forget about it