On this page12 sections
Lecture 018: The If-Null Operator ??
| Day | 7: Conditional Expressions & switch |
| Lecture | 018 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
"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 andint.tryParse - Know how
??differs from the ternary operator
1. The Shape
value ?? fallbackIf value is not null, the result is value. If it is null, the result is fallback.
String? nickname;
var display = nickname ?? 'Guest';
print(display); // Guest
nickname = 'Sunny';
print(nickname ?? 'Guest'); // SunnyIt's a short way to write a ternary:
var display = nickname != null ? nickname : 'Guest';2. Common Uses
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:
String? phone;
String? email;
var contact = phone ?? email ?? 'No contact info';
print(contact); // No contact info4. ??= : Fill In Only If Empty
a ??= b means "if a is null, set it to b; otherwise leave it alone":
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:
String? empty = '';
print(empty ?? 'default'); // prints an empty line, not "default"Code Examples
Example 1: Loading Saved Preferences
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
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
var name = 'Ali';
print(name ?? 'Guest');It runs and prints Ali, but dart analyze warns:
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 +
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
int? a;What isa ?? 7?int? b = 3;What isb ?? 7?- What does
null ?? null ?? 'last'give? String? city = 'Quetta'; city ??= 'Lahore';What iscity?- Write one line that reads
stock['Pen']from aMap<String, int>, using0if it's missing. - What does
print('' ?? 'none');print?
Practice Answers
73lastQuettavar pens = stock['Pen'] ?? 0;- An empty line.
''isn'tnull.
Key Takeaways
a ?? b=a, unlessais null, thenb.- Chain fallbacks:
a ?? b ?? ctakes the first non-null value. a ??= bfills inaonly if it's null.- Perfect for map lookups,
tryParseand optional settings. ??reacts tonullonly, not to empty strings.