typestar

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

  1. A map lookup returns String? — the key might be absent.
  2. ?. stops at null; ?? supplies the fallback.
  3. After if (bittern != null) the type promotes to plain String.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Null safety, step 16 of 27 in Language basics.

← Previous Next →

Nullable types in other languages