0

Why does Dart say the _parent variable is potentially null when there is a trivial if..then checking? How to get past this problem?

class Scope {
    late final Map _map;
    Scope? _parent;

    Scope() : _map = {};

    bool has(String key) {
        if (_map.containsKey(key)) {
            return true;
        }
        if (_parent == null) {
            return false;
        } else { 
            return _parent.has(key);
        }
    }
}

void main() {
    return;
}
$ dart run bug.dart
bug.dart:14:47: Error: Method 'has' cannot be called on 'Scope?' because it is potentially null.
 - 'Scope' is from 'bug.dart'.
Try calling using ?. instead.
            return _parent != null && _parent.has(key);
                                              ^^^

A simple null safety question.

Hamed
  • 5,867
  • 4
  • 32
  • 56
B So
  • 1

1 Answers1

0

Use the null-aware operator ?. when calling the has method on _parent to avoid the error message:

return _parent?.has(key) ?? false;
Hamed
  • 5,867
  • 4
  • 32
  • 56