Nullable types in Dart
String? admits null; the compiler tracks which one you hold.
// String? admits null; plain String never does. A map lookup is the
// classic source: the key might not be there.
String? lastFixFor(Map<String, String> log, String species) =>
log[species];
void main() {
final log = {'bittern': 'north scrape'};
final heron = lastFixFor(log, 'heron');
final bittern = lastFixFor(log, 'bittern');
// ?. stops at null; ?? supplies the fallback.
print(heron?.toUpperCase() ?? 'no fix logged');
print(bittern?.toUpperCase() ?? 'no fix logged');
// Promotion: after the check, bittern is plain String.
if (bittern != null) {
print('Fix is ${bittern.length} chars');
}
}
How it works
- A map lookup returns
String?— the key might be absent. ?.stops at null;??supplies the fallback.- After
if (bittern != null)the type promotes to plainString.
Keywords and builtins used here
Stringfinalifvoid
The run, in numbers
- Lines
- 19
- Characters to type
- 603
- Tokens
- 121
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 104 seconds.
Step 1 of 3 in Null safety, step 16 of 27 in Language basics.