Dart null safety doesn’t work with class fields [duplicate]

The problem is that class fields can be overridden even if it is marked as final. The following example illustrates the problem:

class A {
  final String? text="hello";

  String? getText() {
    if (text != null) {
      return text;
    } else {
      return 'WAS NULL!';
    }
  }
}

class B extends A {
  bool first = true;

  @override
  String? get text {
    if (first) {
      first = false;
      return 'world';
    } else {
      return null;
    }
  }
}

void main() {
  print(A().getText()); // hello
  print(B().getText()); // null
}

The B class overrides the text final field so it returns a value the first time it is asked but returns null after this. You cannot write your A class in such a way that you can prevent this form of overrides from being allowed.

So we cannot change the return value of getText from String? to String even if it looks like we checks the text field for null before returning it.

Leave a Comment