Null check operator used on a null value when checking with if

Issue

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');
}

Solution

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;
      }
    });
  }

Answered By – nvoigt

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *