Search code examples
flutterdartdart-null-safetynull-check

dart null checking: why do i have to use a null check operator ('!') after checking already for null ( != null )


I updated my flutter project to nullsafety and get errors saying:

The function can't be unconditionally invoked because it can be 'null'. Try adding a null check ('!').

For a variable that I already checked for null. What is the correct way to do this now? I know I can just add ! because i know it can't be null. But I don't see why. If there was more code it could happen, that the null check is deleted and the ! operator stays.

Here is my code example:

final Function? suggestionsCallback;

if (widget.suggestionsCallback != null &&
    widget.defaultSearchPattern.isNotEmpty &&
    pattern.isEmpty) {
          return await widget.suggestionsCallback(widget.defaultSearchPattern); // here is the error

    } else {
          return widget.suggestionsCallback != null
              ? await widget.suggestionsCallback(pattern) // here is the error
              : [];
    }

Solution

  • Take a quick look at my code:

    class Hello{
      final Function? hello;
    
      Hello(this.hello);
    }
    
    class Say{
      wow(){
        var h1 = Hello(null);
        if(h1.hello!=null) h1.hello();
      }
    }
    

    Error Prompt

    https://dart.dev/tools/non-promotion-reasons#property-or-this

    Note: "Promotion" here means "determine that a nullable is in fact not null at this line of code";

    Dart compiler is not smart enough to infer that your function, after the if-statement, is NOTNULL at that position of your code. It can only tell a local variable is not null after certain condition statements.