Sub topic 8
Turning state into widgets
This chapter assumes you can write a Dart 3 sealed class hierarchy and a switch expression over it. It also assumes you know StatelessWidget, StatefulWidget, and setState. Here you connect the two. A sealed state object goes in, and a widget subtree comes out.
The shape of the mapping
A screen that loads data is in exactly one situation at a time. It is loading, it has data, or it has failed. If the state type has one variant per situation, build can be one switch expression with one branch per variant.
The compiler checks the switch. If you add a fourth variant to the sealed class, every switch over it stops compiling until you handle the new case. The compiler becomes a checklist of the screens you must update.
The state type
These are the variants from earlier chapters, repeated here so the file runs on its own:
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;
}A pure view widget
Start with a widget that only renders. It takes a state and a retry callback, and it holds no state of its own.
import 'package:flutter/material.dart';
class ItemsView extends StatelessWidget {
const ItemsView({super.key, required this.state, required this.onRetry});
final LoadState<List<String>> state;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
return switch (state) {
Loading() => const Center(child: CircularProgressIndicator()),
Loaded(data: final items) when items.isEmpty =>
const Center(child: Text('Nothing here yet')),
Loaded(data: final items) => ListView(
children: [for (final item in items) ListTile(title: Text(item))],
),
Failed(error: final e) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Something went wrong: $e'),
const SizedBox(height: 8),
FilledButton(onPressed: onRetry, child: const Text('Retry')),
],
),
),
};
}
}Three details are worth noticing:
- The
switchis an expression, so it can followreturndirectly. Each branch yields aWidget, and Dart infers the common type. - The
when items.isEmptyguard comes before the unguardedLoadedcase. Dart checks cases from top to bottom, so the general case must come last. Loaded(data: final items)bindsitemsasList<String>. You don't cast, anditemsdoesn't exist in branches where it would be meaningless. TheLoadingbranch can't reachdataat all.
Because ItemsView is a pure function of its inputs, you can test it with a widget test by passing each state in turn. No network or timers are involved.
Owning the state
The widget that owns the state decides when it changes. This host starts in Loading, fails on the first attempt, and succeeds on the retry. That lets you see every branch.
void main() => runApp(const MaterialApp(home: ItemsScreen()));
class ItemsScreen extends StatefulWidget {
const ItemsScreen({super.key});
@override
State<ItemsScreen> createState() => _ItemsScreenState();
}
class _ItemsScreenState extends State<ItemsScreen> {
LoadState<List<String>> _state = const Loading();
int _attempts = 0;
@override
void initState() {
super.initState();
_load();
}
Future<List<String>> _fetch() async {
await Future<void>.delayed(const Duration(seconds: 1));
if (_attempts++ == 0) throw Exception('network down');
return ['Apples', 'Bread', 'Milk'];
}
Future<void> _load() async {
setState(() => _state = const Loading());
try {
final items = await _fetch();
if (!mounted) return;
setState(() => _state = Loaded(items));
} catch (e) {
if (!mounted) return;
setState(() => _state = Failed(e));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Shopping list')),
body: ItemsView(state: _state, onRetry: _load),
);
}
}Place this code after the LoadState classes and ItemsView in one file, with import 'package:flutter/material.dart'; at the top. Run it. You see a spinner, then an error with a Retry button, then the list.
The mounted checks matter. The await can finish after the user has left the screen, and calling setState on a disposed State throws.
Why the switch lives in build
The switch is in build for a reason. build must be a pure description of the current state, so it should not start requests or change fields. The switch only reads state and returns widgets. Side effects belong in event handlers such as _load, which assign a new state value inside setState.
Keeping the UI honest as the state grows
Suppose you want pull-to-refresh that keeps the old list visible while reloading. The tempting fix is a bool isRefreshing field on Loaded. That brings back the flag problem from the start of the tutorial.
A better fix is a new variant:
final class Refreshing<T> extends LoadState<T> {
const Refreshing(this.previous);
final T previous;
}Every switch over LoadState now fails to compile until it handles Refreshing. In the view, the new branch can render the same list as Loaded with a thin progress bar above it. The compile errors tell you where to look, and no screen can forget the new situation.
Extract per-state widgets once a branch grows past a few lines, so the switch stays readable:
Failed(error: final e) => ErrorPanel(error: e, onRetry: onRetry),Keep the switch as a table of contents and put the detail in small widgets.
Animating between states
A plain switch swaps subtrees instantly. AnimatedSwitcher can fade between them, but it needs to know when the child has changed. It compares the widget's type and key, and nothing else.
AnimatedSwitcher(
duration: const Duration(milliseconds: 250),
child: switch (state) {
Loading() => const Center(
key: ValueKey('loading'),
child: CircularProgressIndicator(),
),
Loaded(data: final items) => ListView(
key: const ValueKey('loaded'),
children: [for (final item in items) ListTile(title: Text(item))],
),
Failed(error: final e) => Center(
key: const ValueKey('failed'),
child: Text('Something went wrong: $e'),
),
},
)Without the keys, a change from one Center to another Center would not animate, because the type matches. Give each variant a distinct key.
Common mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| `_ => SizedBox()` as a catch-all branch | New variants silently render nothing, and the compiler no longer warns you | List every variant. Use `_` only where a blank result is a deliberate choice |
| Guard cases after the unguarded case | The guarded branch is unreachable, and the analyzer reports it | Put `when` cases before the general case for the same variant |
| Starting a fetch inside `build` | A request fires on every rebuild | Start work in `initState` or an event handler |
| Calling `setState` after `await` without `mounted` | Exception when the widget is gone | Check `mounted` before `setState` |
| Casting with `state as Loaded` in the UI | A runtime error replaces the compile-time check | Destructure with a pattern |
| Using one `Center` per branch under `AnimatedSwitcher` without keys | No animation | Add a `ValueKey` per variant |
Generics in the view
Because LoadState<T> is generic, the same pattern works for any data. A profile screen would use LoadState<UserProfile> and the same three branches. If many screens share the layout of spinner, error, and content, you can write a reusable widget that takes the content builder as a parameter:
class LoadStateView<T> extends StatelessWidget {
const LoadStateView({
super.key,
required this.state,
required this.onRetry,
required this.builder,
});
final LoadState<T> state;
final VoidCallback onRetry;
final Widget Function(BuildContext context, T data) builder;
@override
Widget build(BuildContext context) {
return switch (state) {
Loading() => const Center(child: CircularProgressIndicator()),
Loaded(data: final data) => builder(context, data),
Failed(error: final e) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Error: $e'),
FilledButton(onPressed: onRetry, child: const Text('Retry')),
],
),
),
};
}
}The trade-off is flexibility. Screens that need a custom empty state or a custom error layout fit a hand-written switch better. A shared widget suits screens that behave the same way.
Exercise
Your ItemsView switch has branches for Loading, Loaded, and Failed. A teammate adds final class Idle<T> extends LoadState<T> for "no request made yet". What happens when you compile, and what is the wrong way to make it pass?
Show answer
The compiler reports that the switch is not exhaustive, because the Idle case is unmatched. The wrong fix is to add a _ => SizedBox() or default branch, which hides the error and also hides any future variants. The right fix is to add an Idle() branch that renders the intended widget, for example a button that starts the load.
Exercise
In the AnimatedSwitcher example, Loaded shows a ListView. The list is replaced by a new Loaded with different items, and you want a cross-fade. Why does nothing animate, and how do you fix it?
Show answer
AnimatedSwitcher treats two children as the same when their type and key match, and both are ListView with the same ValueKey('loaded'). Make the key depend on the data, for example ValueKey(items), or on a version number or id, so each new list counts as a new child.