Sub topic 4
Switch expressions over a sealed type
A switch expression turns a sealed state value into a result, and the compiler checks that every variant is handled. This chapter covers the syntax, how Dart picks an arm, how the result type is inferred, and the errors you will meet in practice.
Prerequisites
This chapter assumes you can already:
- Write Dart classes with constructors and
finalfields, and use null safety. - Read basic generics such as
List<String>andLoadState<T>. - Declare a
sealedclass and its subclasses, as in the previous two chapters.
You need Dart 3 or later. Switch expressions and patterns do not exist in Dart 2.
The type we will switch over
All examples use the loading-state hierarchy from the previous chapter. Each state carries only the data that makes sense for it.
sealed class LoadState<T> {
const LoadState();
}
final class Loading<T> extends LoadState<T> {
const Loading();
}
final class Loaded<T> extends LoadState<T> {
const Loaded(this.data);
final T data;
}
final class Failed<T> extends LoadState<T> {
const Failed(this.error);
final Object error;
}Because LoadState is sealed, the compiler knows the complete list of direct subtypes: Loading, Loaded and Failed. That closed list is what makes the checks below possible.
Statements versus expressions
Dart has had switch statements for a long time. Dart 3 adds the switch expression, which is a value you can return, assign, or pass as an argument.
| Feature | Switch statement | Switch expression |
|---|---|---|
| Produces a value | No | Yes |
| Arm syntax | `case Pattern:` followed by statements | `Pattern => expression,` |
| Separator between arms | None, each case ends at the next `case` | Comma |
| Needs `break` | No in Dart 3 | Not applicable |
| Exhaustive over sealed types | Yes | Yes |
| Can contain several statements per arm | Yes | No, one expression per arm |
Prefer the expression whenever the goal is to compute a value. It cannot forget to produce a result for one branch, because every arm must supply one.
Your first switch expression
Here is a function that turns any LoadState into a label.
String label(LoadState<Object?> state) => switch (state) {
Loading() => 'Loading...',
Loaded() => 'Loaded',
Failed() => 'Failed',
};
void main() {
print(label(const Loading<int>()));
print(label(const Loaded<int>(3)));
print(label(Failed<int>(StateError('boom'))));
}Running it prints:
Loading...
Loaded
FailedRead the syntax from left to right:
switch (state)names the value being matched, called the scrutinee.- Each arm has a pattern, then
=>, then the expression whose value becomes the result. - Arms are separated by commas. A trailing comma after the last arm is allowed and is what the formatter produces.
- There is no
casekeyword, nodefault, and nobreak.
The parameter type is LoadState<Object?>. Dart generics are covariant, so a LoadState<int> or LoadState<List<String>> can be passed here. That makes label usable for any payload type.
How Dart chooses an arm
Dart tests the arms from top to bottom and runs the first one that matches. It then stops. The order therefore matters whenever two patterns could match the same value.
The last box matters. With a sealed type, the compiler proves before the program runs that the final test cannot fail. You do not need a fallback arm.
If an earlier pattern already covers everything a later one would match, Dart reports the later arm as unreachable. For example, putting LoadState() => 'any' first makes the three arms after it dead code.
Using the matched value
An arm often needs data from the variant. A pattern can bind that data to a new variable. The next chapter covers object patterns in depth. This preview shows the shape you will use most.
int? valueOrNull(LoadState<int> state) => switch (state) {
Loaded<int>(data: final d) => d,
Loading() || Failed() => null,
};Two things happen here:
Loaded<int>(data: final d)matches aLoadedobject and binds itsdatafield to a variable namedd. The variable exists only inside that arm.Loading() || Failed()is an or-pattern. It lets two variants share one result.
A single arm can only be one expression. When you need more than that, call a helper function or compute the work before the switch.
The result type is inferred
The type of a switch expression is the closest common supertype of all its arms, unless the surrounding context fixes the type.
Object mixed(LoadState<Object?> state) {
final result = switch (state) {
Loading() => 0,
Loaded() => 'ok',
Failed() => 'bad',
};
return result;
}Here result has type Object, because the arms return int and String. This compiles, but it is rarely what you meant. Give the function a precise return type, or annotate the variable, so a stray arm of the wrong type becomes an error at that arm instead of a surprise later.
An arm may also be a throw expression. A throw has the bottom type Never, so it fits any result type and does not widen the result.
T requireData<T>(LoadState<T> state) => switch (state) {
Loaded<T>(data: final d) => d,
Loading<T>() => throw StateError('Still loading'),
Failed<T>(error: final e) => throw e,
};Use this pattern for functions that should only be called in a state you have already verified. Otherwise, prefer returning a nullable or a default so callers cannot crash.
What the compiler checks
Delete the Failed() arm from label and the file no longer compiles. The error says the switch does not exhaustively match the type and names the missing subtype, Failed<Object?>(). The exact wording differs between Dart versions.
The same check protects you when the hierarchy grows. Suppose you add a fourth variant:
final class Refreshing<T> extends LoadState<T> {
const Refreshing(this.previous);
final T previous;
}Every switch over LoadState that lacks a Refreshing arm now fails to compile. You get a complete list of places that need a decision before the app runs.
A switch statement gets the same check in Dart 3 when its scrutinee is a sealed type:
void log(LoadState<Object?> state) {
switch (state) {
case Loading():
print('waiting');
case Loaded():
print('done');
case Failed():
print('error');
}
}Each case ends on its own, so you do not write break. Use the statement form when each branch performs side effects such as logging and no value is needed.
Common errors
- Adding a wildcard
_arm "to make the error go away". A wildcard matches every remaining value, so the compiler stops reporting missing variants. A new subclass will then fall into the wildcard silently. List each variant instead. - Putting a broad pattern first. The first matching arm wins, so a general pattern above specific ones hides them. Dart warns about the unreachable arms. Treat that warning as a bug.
- Using a semicolon or
casein an expression. Arms in a switch expression end with a comma, andcasebelongs to the statement form. - Expecting statements in an arm. An arm holds one expression. Move multi-step logic into a function and call it.
- Letting the result type widen. Mixed arm types produce
ObjectorObject?. Declare the return type you intend. - Switching on a type that is not sealed. Over an ordinary class or an
abstractclass, the compiler cannot know all subtypes, so it requires a default or wildcard arm. The sealed modifier is what removes that requirement.
Summary of the working model
A switch expression takes a value, tests patterns in order, and yields the value of the first match. Over a sealed type, the compiler also proves that some arm always matches. Together these give you a function from state to result in which a forgotten case is a compile error.
Exercise
You have sealed class Shape {} with final subclasses Circle(this.radius) and Square(this.side), both with final double fields. Write double area(Shape s) as a switch expression. Then explain what happens when you add Triangle to the hierarchy and leave area unchanged.
Show answer
One correct answer is double area(Shape s) => switch (s) { Circle(radius: final r) => 3.14159 * r * r, Square(side: final a) => a * a };. After you add Triangle, area stops compiling. The compiler reports that the switch is not exhaustive and names Triangle() as the unmatched case. You fix it by adding a Triangle arm. A _ arm would hide the error, which is why you should not add one.
Exercise
A teammate writes final label = switch (state) { Loading() => 0, Loaded() => 'ok', Failed() => 'bad' };. What is the static type of label, and how would you make the compiler catch the mismatch?
Show answer
The static type is Object, because it is the closest common supertype of int and String. Declare the type you intend, for example final String label = switch (...), or return the switch from a function with a return type of String. The 0 arm is then reported as a type error.