Switch Expressions & Exhaustiveness
A switch expression is a switch that produces a value. Combined with sealed classes, enums and patterns, it gives Dart one of its most expressive features: concise branching that the compiler proves is complete.
Switch statement vs switch expression
enum Weather { sunny, cloudy, rainy, stormy }
// Statement: runs code, needs a variable and assignments
String adviceOld(Weather w) {
String result;
switch (w) {
case Weather.sunny:
result = 'sunglasses';
case Weather.cloudy:
result = 'light jacket';
case Weather.rainy || Weather.stormy:
result = 'umbrella';
}
return result;
}
// Expression: evaluates to a value
String advice(Weather w) => switch (w) {
Weather.sunny => 'sunglasses',
Weather.cloudy => 'light jacket',
Weather.rainy || Weather.stormy => 'umbrella',
};
void main() {
for (final w in Weather.values) {
print('${w.name}: ${advice(w)} / ${adviceOld(w)}');
}
}sunny: sunglasses / sunglasses
cloudy: light jacket / light jacket
rainy: umbrella / umbrella
stormy: umbrella / umbrella
Syntax differences in a switch expression:
| Statement | Expression |
|---|---|
case pattern: |
pattern => (no case keyword) |
| Body is statements | Body is a single expression |
| Cases end without commas | Cases are separated by commas (trailing comma allowed) |
default: |
_ => |
| Can be non-exhaustive (for most types) | Must be exhaustive |
Exhaustiveness
A switch expression must produce a value for every possible input, so the compiler checks that the cases are exhaustive. It understands:
bool(true/false), enums and nullable types (null)- sealed class hierarchies
- record and list shapes, combined field by field
- wildcards
_and plain type patterns (int _)
String classify(int? n) => switch (n) {
null => 'missing',
< 0 => 'negative',
0 => 'zero',
> 0 => 'positive',
_ => 'impossible', // ints can't be proven exhaustive by ranges alone
};
String combine(bool a, bool b) => switch ((a, b)) {
(true, true) => 'both',
(true, false) || (false, true) => 'one',
(false, false) => 'neither',
};
void main() {
print([null, -3, 0, 8].map(classify).toList());
print(combine(true, false));
print(combine(false, false));
}[missing, negative, zero, positive]
one
neither
Two things to notice:
classifyneeds_at the end: relational patterns like< 0and> 0do cover every int, but the compiler doesn't reason about numeric ranges, so it can't prove that.combineneeds no wildcard: the record cases(true, true),(true, false) || (false, true)and(false, false)cover all four combinations of twobools, and the compiler can check that field by field.
Modelling with sealed classes
The classic use case: a closed family of states or events, each with its own data.
sealed class Shape {}
class Circle extends Shape {
final double radius;
Circle(this.radius);
}
class Rect extends Shape {
final double w, h;
Rect(this.w, this.h);
}
class Triangle extends Shape {
final double a, b, c;
Triangle(this.a, this.b, this.c);
}
double perimeter(Shape s) => switch (s) {
Circle(:final radius) => 2 * 3.14159 * radius,
Rect(:final w, :final h) when w == h => 4 * w,
Rect(:final w, :final h) => 2 * (w + h),
Triangle(:final a, :final b, :final c) => a + b + c,
};
void main() {
final shapes = [Circle(1), Rect(2, 2), Rect(2, 5), Triangle(3, 4, 5)];
for (final s in shapes) {
print('${s.runtimeType}: ${perimeter(s).toStringAsFixed(2)}');
}
}Circle: 6.28
Rect: 8.00
Rect: 14.00
Triangle: 12.00
Note that a case with a when guard doesn't count towards exhaustiveness — the guard might be false. The unguarded Rect(...) case after it makes the switch complete.
A tiny state machine
Switch expressions on records make state transitions read like a table:
enum Light { off, on, blinking }
enum Button { power, mode }
Light next(Light state, Button pressed) => switch ((state, pressed)) {
(Light.off, Button.power) => Light.on,
(Light.off, Button.mode) => Light.off,
(_, Button.power) => Light.off,
(Light.on, Button.mode) => Light.blinking,
(Light.blinking, Button.mode) => Light.on,
};
void main() {
var state = Light.off;
for (final b in [Button.mode, Button.power, Button.mode, Button.mode, Button.power]) {
state = next(state, b);
print('${b.name.padRight(5)} -> ${state.name}');
}
}mode -> off
power -> on
mode -> blinking
mode -> on
power -> off
When the compiler says "not exhaustive"
enum Level { debug, info, warning, error }
String tag(Level l) => switch (l) {
Level.debug => 'D',
Level.info => 'I',
Level.warning => 'W',
};
void main() => print(tag(Level.error));example.dart:3:32: Error: The type 'Level' is not exhaustively matched by the switch cases since it doesn't match 'Level.error'.
- 'Level' is from 'example.dart'.
Try adding a wildcard pattern or cases that match 'Level.error'.
String tag(Level l) => switch (l) {
^
Error: AOT compilation failed
Bad state: Generating AOT kernel dill failed!
The message names the exact missing case. Resist the urge to "fix" it with _ => — an explicit case keeps the safety net for values you add in the future.
Tip: Avoid
_ =>(ordefault) on enums and sealed types unless you truly want a catch-all. Without it, adding a new value turns every unhandled switch into a compile error — a to-do list generated by the compiler.
Test yourself
How is the default case written in a switch expression?
- default =>
- _ =>
- else =>
- case _:
Does a case with a when guard count towards exhaustiveness?
- Yes, always
- No, because the guard might be false
- Only for enums
- Only if it's the last case
Why can a switch over a sealed class omit _?
- Sealed classes can't be null
- The compiler knows every direct subtype, so it can prove the cases cover them all
- Sealed classes have only one subtype
- Switch expressions never need a default