2

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
              : [];
    }
fiona
  • 543
  • 4
  • 8

2 Answers2

1

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.

linkfting
  • 164
  • 8
-1

You know the variable can’t be null because you just checked. The compiler doesn’t. So unfortunately you have to tell it again.

Actually your specific compiler might be clever enough, but not all compilers are. And whether you have compile time errors shouldn’t depend on how clever the compiler is. Therefore the language will require the ! test. It’s quite possible that the compiler produced no actual test for the !

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • 1
    The Dart compiler can do type promotion *for local variables*. For *member* variables, it's impossible (regardless of compiler cleverness) since the member access involves virtual dispatch that can be resolved only at runtime, and there's no telling if the member access might return different values each time (even though doing so would be a bad design). – jamesdlin Sep 02 '21 at 07:48