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.

0

1 Answer 1

0

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

return _parent?.has(key) ?? false;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.