Sub topic 8
Turning state into widgets
Assume you know Dart classes, null safety, generics, Flutter widgets, and the build method. This chapter uses Dart 3 pattern matching and the sealed LoadState<T> type from the previous examples.
A Flutter screen often displays one of several states:
- A request is still running.
- Data loaded successfully.
- The request failed.
A sealed state type lets the widget map each state to exactly one subtree. This keeps rendering logic in one visible place and prevents a newly added state from being silently ignored.
Return a widget from an exhaustive switch
The build method can return a switch expression directly. Each pattern both identifies a state variant and extracts the data needed to build its widgets.
import 'package:flutter/material.dart';
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;
}
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) when items.isEmpty => const Center(
child: Text('No items yet'),
),
Loaded(data: final items) => ListView(
children: [
for (final item in items)
ListTile(title: Text(item)),
],
),
Failed(error: final error) => Center(
child: Text('Could not load items: $error'),
),
};
}
}
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Items')),
body: const ItemsView(
state: Loaded(['Apples', 'Oranges']),
),
),
);
}
}
void main() {
runApp(const ExampleApp());
}Loaded(data: final items) is an object pattern. It reads the data field and binds it to the local variable items. The when clause is a guard. It restricts the first Loaded case to an empty list.
Case order matters. The guarded empty case must come before the general Loaded case. Otherwise, the general case would match every loaded value first.
Keep state-specific behavior with the state
The loading branch should not read data that loading does not contain. The error branch should not assume that a successful result exists. Each subclass defines which fields are valid, and the pattern match exposes only those fields.
This is safer than a widget that receives fields such as isLoading, items, and error, where combinations like “loading with an error and old items” are possible.
Check one variant with if-case
Use if-case when a method needs to respond to one state and does not need a full UI mapping.
void printFirstItem(LoadState<List<String>> state) {
if (state case Loaded(data: final items) when items.isNotEmpty) {
print(items.first);
}
}The other variants do nothing. Use a complete switch when every state must produce a result, such as a widget or a status label.
Common mistakes
- Put the broad
Loadedpattern before a guardedLoadedpattern. - Use
state.datawithout first proving thatstateis loaded. - Return
SizedBox()for an unplanned state instead of handling it explicitly. - Forget that adding a subclass changes every exhaustive switch in the same library.
- Display raw exception text when it may reveal internal or sensitive details.
Testing the widget mapping does not require a network request. Construct Loading, Loaded, and Failed values directly, then verify the expected widget or visible text.
Exercise
What happens if a new Refreshing subclass is added to LoadState but ItemsView is not updated?
Show answer
The exhaustive switch stops compiling, requiring the widget to define how Refreshing should be displayed.