Sub topic 4
Switch expressions over a sealed type
Prerequisites
This chapter assumes Dart 3 or later, basic classes and null safety, simple generics, and basic Flutter widgets. A sealed class is a class whose direct subtypes are known to the compiler. We use one to represent a closed set of loading states.
A switch statement performs actions. A switch expression produces a value. This makes a switch expression useful when a function or widget must choose one result from several state variants.
Replacing conditional flags
A flag-based model might store isLoading, items, and error separately. That model can describe contradictory combinations, such as loading while also showing an error. A sealed hierarchy gives each valid state its own type.
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;
}
String describe(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) => '${items.length} items loaded',
Failed(error: final error) => 'Error: $error',
};
void main() {
print(describe(const Loading<List<String>>()));
print(describe(const Loaded<List<String>>(['A', 'B'])));
print(describe(const Failed<List<String>>('Network unavailable')));
}The switch expression follows => and contains one arm for each possible variant. Each arm has a pattern on the left and a result on the right. The whole expression returns a String, so describe can use it directly as its return value.
Loading() matches an object whose type is Loading. Loaded(data: final items) matches a Loaded object and binds its data field to the local variable items. The binding exists only inside that arm.
The commas separate the arms. The final semicolon belongs to the function declaration.
Exhaustiveness checking
Because LoadState is sealed, Dart can check whether the switch handles every direct subtype. If you add this new state:
final class Empty<T> extends LoadState<T> {
const Empty();
}the describe function must add an Empty() arm before it can compile again.
This check is valuable because state changes often require a user-interface decision. A newly added state should not silently fall through to a misleading screen.
How the matching works
The cases are tested from top to bottom. The first matching pattern supplies the result.
Keep overlapping patterns in mind. A broad pattern placed before a specific pattern can make the specific case unreachable or prevent it from being selected. Put more specific cases first when several patterns could match.
Using the result in Flutter
A Flutter widget can return a different subtree for each state:
class ItemsView extends StatelessWidget {
const ItemsView({
super.key,
required this.state,
});
final LoadState<List<String>> state;
@override
Widget build(BuildContext context) {
return switch (state) {
Loading() => const Center(
child: CircularProgressIndicator(),
),
Loaded(data: final items) => ListView(
children: [
for (final item in items) ListTile(title: Text(item)),
],
),
Failed(error: final error) => Center(
child: Text('Something went wrong: $error'),
),
};
}
}The build method returns a Widget, and every switch arm returns a widget. When a new state is added, the compiler points to this method and requires a UI decision.
Exercise
Why is switch (state) safer here than checking isLoading and then checking whether error is null?
Show answer
The sealed state allows only one known variant at a time, and exhaustiveness checking requires the code to handle every variant.