Question #128EasyDart BasicsImportant

What is the null coalescing operator ? Ans: '??' to provide "" as a default value.

Answer

Overview

The null coalescing operator

text
??
in Dart returns the left-hand value if it's not null, otherwise returns the right-hand value (the fallback/default).


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 ??

dart
String? 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:

dart
String? 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

OperatorNameBehavior
text
??
Null coalescingReturn left if not null, else right
text
??=
Null assignmentAssign to variable only if null
text
?.
Null-aware accessCall method/property only if not null
text
!
Null assertionAssert not null (throws if null)

Best Practice: Use

text
??
to provide safe defaults for nullable values. Pair
text
?.
with
text
??
for safe access + meaningful defaults:
text
user?.name ?? 'Guest'
.