On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Shape
  4. 2. Common Uses
  5. 3. Chaining Fallbacks
  6. 4. ??= : Fill In Only If Empty
  7. 5. null Is Not the Same as Empty
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 018: The If-Null Operator ??

Day7: Conditional Expressions & switch
Lecture018 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

"Use the user's nickname, or 'Guest' if they don't have one." That sentence is the whole job of ??. It's a conditional expression made for nullable values, and you'll use it constantly with maps, forms and saved settings.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 010 (null safety), 014 (maps) and 017 (ternary operator).


Learning Objectives

  • Give a default for a nullable value with a ?? b
  • Chain several fallbacks: a ?? b ?? c
  • Fill in a variable only when it's null, with ??=
  • Use ?? with maps and int.tryParse
  • Know how ?? differs from the ternary operator

1. The Shape

code
value ?? fallback

If value is not null, the result is value. If it is null, the result is fallback.

dart
String? nickname;
var display = nickname ?? 'Guest';
print(display);   // Guest

nickname = 'Sunny';
print(nickname ?? 'Guest');   // Sunny

It's a short way to write a ternary:

dart
var display = nickname != null ? nickname : 'Guest';

2. Common Uses

dart
int? savedVolume;
var volume = savedVolume ?? 50;
print(volume);   // 50

var settings = {'theme': 'dark'};
print(settings['theme'] ?? 'light');       // dark
print(settings['language'] ?? 'English');  // English (missing key)

print(int.tryParse('abc') ?? -1);          // -1 (couldn't parse)

Maps (Lecture 014) and int.tryParse (Lecture 010) both give null when something is missing, and ?? turns that into a sensible default.

3. Chaining Fallbacks

?? can be chained. Dart takes the first value that isn't null:

dart
String? phone;
String? email;
var contact = phone ?? email ?? 'No contact info';
print(contact);   // No contact info

4. ??= : Fill In Only If Empty

a ??= b means "if a is null, set it to b; otherwise leave it alone":

dart
int? score;
score ??= 0;
print(score);   // 0
score ??= 100;
print(score);   // 0 (already had a value)

5. null Is Not the Same as Empty

?? reacts only to null. An empty string '' is a real value:

dart
String? empty = '';
print(empty ?? 'default');   // prints an empty line, not "default"

Code Examples

Example 1: Loading Saved Preferences

dart
void main() {
  // Saved preferences: missing ones are null
  var saved = <String, String>{'name': 'Hamza', 'theme': 'dark'};

  var name = saved['name'] ?? 'Guest';
  var theme = saved['theme'] ?? 'light';
  var fontSize = int.tryParse(saved['fontSize'] ?? '') ?? 16;
  var language = saved['language'] ?? saved['region'] ?? 'English';

  print('Hello, $name');
  print('Theme: $theme');
  print('Font size: $fontSize');
  print('Language: $language');

  saved['language'] ??= 'Urdu';
  saved['theme'] ??= 'light';
  print(saved);
}

Output

code
Hello, Hamza
Theme: dark
Font size: 16
Language: English
{name: Hamza, theme: dark, language: Urdu}

saved['language'] ??= 'Urdu' added the missing key; saved['theme'] ??= 'light' left dark alone. int.tryParse(saved['fontSize'] ?? '') ?? 16 has two steps: a missing setting becomes '', which doesn't parse, so the result falls back to 16.


Common Beginner Mistakes

1. Using ?? on a value that can't be null

dart
var name = 'Ali';
print(name ?? 'Guest');

It runs and prints Ali, but dart analyze warns:

code
warning - The left operand can't be null, so the right operand is never executed.

?? only makes sense on nullable values (String?, int?, map lookups).

2. Forgetting brackets when mixing with +

dart
String? name = 'Hi';
print(name ?? 'Guest' + '!');     // Hi
print((name ?? 'Guest') + '!');   // Hi!

+ is worked out before ??, so the first line means name ?? ('Guest' + '!'). Add brackets to say what you mean.

3. Expecting ?? to catch empty strings: '' ?? 'default' is ''. Check isEmpty if empty text should also use the default.

4. Confusing ??= with =: x ??= 5 doesn't change x when it already has a value.


Practice Questions

  1. int? a; What is a ?? 7?
  2. int? b = 3; What is b ?? 7?
  3. What does null ?? null ?? 'last' give?
  4. String? city = 'Quetta'; city ??= 'Lahore'; What is city?
  5. Write one line that reads stock['Pen'] from a Map<String, int>, using 0 if it's missing.
  6. What does print('' ?? 'none'); print?

Practice Answers

  1. 7
  2. 3
  3. last
  4. Quetta
  5. var pens = stock['Pen'] ?? 0;
  6. An empty line. '' isn't null.

Key Takeaways

  • a ?? b = a, unless a is null, then b.
  • Chain fallbacks: a ?? b ?? c takes the first non-null value.
  • a ??= b fills in a only if it's null.
  • Perfect for map lookups, tryParse and optional settings.
  • ?? reacts to null only, not to empty strings.