Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
      }
    });
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading