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

  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 1:

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!