What is the null coalescing operator ? Ans: '??' to provide "" as a default value.
Answer
Overview
The null coalescing operator
text
??Basic Usage
dart// Syntax: expression ?? defaultValue String? name = null; String result = name ?? 'Guest'; // 'Guest' (name is null) print(result); // Guest String? city = 'Mumbai'; String displayCity = city ?? 'Unknown'; // 'Mumbai' (city is not null) print(displayCity); // Mumbai
?? vs Ternary
dart// Ternary (longer) String label = user != null ? user.name : 'Guest'; // ?? (cleaner for null checks) String label = user?.name ?? 'Guest';
Chaining ??
dartString? first = null; String? second = null; String? third = 'Found it!'; String result = first ?? second ?? third ?? 'Nothing'; print(result); // Found it! — first non-null in chain
??= — Null Assignment Operator
Assigns a value only if the variable is currently null:
dartString? cache; cache ??= fetchExpensiveData(); // Only calls if cache is null // Equivalent to: // if (cache == null) { cache = fetchExpensiveData(); } // Common initialization pattern _controller ??= AnimationController(vsync: this);
Real-World Usage
dart// API response with defaults Map<String, dynamic> json = {'name': 'Alice'}; final name = json['name'] as String? ?? 'Unknown'; // Alice final age = json['age'] as int? ?? 0; // 0 (default) final avatar = json['avatar'] as String? ?? 'default.png'; // default.png // User preferences final theme = prefs.getString('theme') ?? 'system'; final fontSize = prefs.getDouble('fontSize') ?? 14.0; // Widget display Text(user?.displayName ?? 'Anonymous User') // Error handling String errorMessage = error?.message ?? 'An unknown error occurred';
?. — Null-Aware Access (Pairs with ??)
dart// Safe method call + fallback final length = someString?.length ?? 0; // Chained null-safe access final country = user?.address?.country ?? 'Unknown'; // Null-safe method call final upper = name?.toUpperCase() ?? 'N/A';
Operators Summary
| Operator | Name | Behavior |
|---|---|---|
text | Null coalescing | Return left if not null, else right |
text | Null assignment | Assign to variable only if null |
text | Null-aware access | Call method/property only if not null |
text | Null assertion | Assert not null (throws if null) |
Best Practice: Use
to provide safe defaults for nullable values. Pairtext??withtext?.for safe access + meaningful defaults:text??.textuser?.name ?? 'Guest'