Null-aware operators in Dart
??=, ?? and ! — the rest of the null toolkit.
void main() {
final counts = <String, int>{'wren': 3};
// ??= assigns only when the current value is null.
int? backupCameras;
backupCameras ??= 1;
print('Backups: $backupCameras');
// Map lookups are nullable; chain the null-aware tools.
final robins = counts['robin'] ?? 0;
print('Robins so far: $robins');
counts['robin'] = robins + 1;
// ! asserts non-null and throws if you were wrong.
final wrens = counts['wren']!;
print('Wrens: $wrens');
}
How it works
??=assigns only when the target is currently null.counts['robin'] ?? 0reads a missing key safely.!asserts non-null and throws if you were wrong — use it sparingly.
Keywords and builtins used here
Stringfinalintvoid
The run, in numbers
- Lines
- 17
- Characters to type
- 450
- Tokens
- 97
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 83 seconds.
Step 2 of 3 in Null safety, step 17 of 27 in Language basics.