CodeBlanks Logo Icon CodeBlanks

Null-aware operators

Learn ??, ?. and ??= operators.

Null-aware operators

Dart, with null safety, offers special operators to handle null: ??, ?. and ??=.

?? returns the right side if the left is null: name ?? 'Guest' — if name is null, returns 'Guest'; otherwise the value of name.

?. accesses a member only if not null: user?.name — if user is null, returns null; otherwise calls name. ??= assigns only if null.

Practice Default with ??

Declare String? name = null;. Print with print(name ?? 'Guest'). Since name is null you should see 'Guest'.

Starter code

main.dart
// Use the ?? operator

Sample solution

main.dart
void main() {
  String? name = null;
  print(name ?? 'Guest');
}

Expected output

Guest

Difference between ?? and ??=

?? returns an expression: name ?? 'Guest' gives a value but does not change name. name is still null.

??= does assignment: name ??= 'Guest'; — if name is null, it sets it to 'Guest'. So if you read name later, you see 'Guest'.

Summary: ?? gives a default when reading; ??= assigns a default when writing. You choose based on your need.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Default operator

Question
String? name; print(name ____ 'Guest');
Answer
String? name; print(name ?? 'Guest');

Explanation: ?? gives the right side if null.

2 What does the ?. operator do?

  • Deletes the variable
  • Forces null
  • Skips the call if null Correct answer
  • Throws an error

Explanation: ?. skips the member call if null; returns null.

3 Null-aware operators

Term Meaning
?? Default
?. Safe call
??= Assign if null
? Nullable

All lessons in Beginner