“The operator can’t be unconditionally invoked because the receiver can be null” error after migrating to Dart null-safety

Dart engineer Erik Ernst says on GitHub:

Type promotion is only applicable to local variables. … Promotion of an instance variable is not sound, because it could be overridden by a getter that runs a computation and returns a different object each time it is invoked. Cf. dart-lang/language#1188 for discussions about a mechanism which is similar to type promotion but based on dynamic checks, with some links to related discussions.

So local type promotion works:

  String myMethod(String? myString) {
    if (myString == null) {
      return '';
    }
    
    return myString;
  }

But instance variables don’t promote. For that you need to manually tell Dart that you are sure that the instance variable isn’t null in this case by using the ! operator:

class MyClass {
  String? _myString;
  
  String myMethod() {
    if (_myString == null) {
      return '';
    }
    
    return _myString!;
  }
}

Leave a Comment