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

How to fix a nullable expression can't be used as a condition error

The following code gives me an error on the line: "rememberMe = newValue" of:
"A value of type ‘bool?’ can’t be assigned to a variable of type ‘bool’."

But if I change the declaration of rememberMe to "bool? rememberMe = false;"
I then get an error on the line:
"if (rememberMe) {" of:
"A nullable expression can’t be used as a condition."

The bool? also creates an issue with the line: "prefs.setBool(‘remember’, rememberMe);"

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

  bool rememberMe = false;
  ...

  setRemberMeValue() async {
    await _getRememberUser();
    if (rememberMe) {
      usernameController.text = userName;
      passwordController.text = password;
      setState(() {
        rememberMe = rememberMe;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final userField = UserTextField(style: style, usernameController: usernameController);
    final passwordField = PasswordTextField(style: style, passwordController: passwordController);
    final rememberMeCheckbox = Checkbox(
      value: rememberMe,
      onChanged: (newValue) {
        setState(() {
          rememberMe = newValue;
        });
      },
    );

>Solution :

This is an issue related to the way Checkbox is written, in theory a checkbox could be either "checked", "unchecked" or "negative checked" (with a cross instead of a check), so the onChanged method returns true if checked, false if unchecked and null if negative-checked.

Because in theory it could be null, you can’t just assign newValue to rememberMe however, your Checkbox will never be negative checked because you didn’t tell it to, so you can be sure newValue will not be null, so you could do something like this:

rememberMe = newValue == true;

This way if newValue was null, null == true would evaluate to false.

However there is a better way to do this!
You can use the null-check operator (!) to tell newValue that it can never be null:

rememberMe = newValue!;

this way, if newValue was null, we would get an exception, but we already know newValue is not null!

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