Sub topic 12
Modeling Loading, Data, and Error State
Assume you know Dart classes, null safety, named parameters, and basic Flutter widget structure. This chapter uses Dart 3 switch expressions and freezed code generation.
A screen that loads remote data usually has more than one meaningful state:
- Loading: the request is in progress.
- Data: the request succeeded and contains usable values.
- Error: the request failed and has an explanation.
A common mistake is to represent these states with separate nullable fields:
String? errorMessage;
List<String>? items;
bool isLoading = false;This allows invalid combinations, such as isLoading == true while items and errorMessage both contain values. A sealed union is a type with a fixed set of alternatives. It makes the valid states explicit.
Define the state union
With freezed, each factory constructor represents one alternative:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'load_state.freezed.dart';
@freezed
sealed class LoadState with _$LoadState {
const factory LoadState.loading() = LoadStateLoading;
const factory LoadState.data(List<String> items) = LoadStateData;
const factory LoadState.error(String message) = LoadStateError;
}The sealed keyword tells Dart that this type has a controlled set of subtypes. Freezed generates the concrete classes and members. Run build_runner after creating or changing this file:
dart run build_runner build --delete-conflicting-outputsThe state type can now describe a request without relying on combinations of flags and nullable values.
| State | Stored value | Typical UI |
|---|---|---|
| `LoadStateLoading` | None | Progress indicator |
| `LoadStateData` | `items` | List of results |
| `LoadStateError` | `message` | Error message and retry action |
Handle every state
Dart's switch expression can match each constructor. Because LoadState is sealed, the analyzer can check that every alternative is handled.
String describeState(LoadState state) => switch (state) {
LoadStateLoading() => 'Loading…',
LoadStateData(:final items) => '${items.length} items loaded',
LoadStateError(:final message) => 'Error: $message',
};The :final items pattern extracts the field from LoadStateData. If you add another constructor, existing exhaustive switches will report an error until you handle the new state.
A Flutter widget can use the same pattern to choose its content:
Widget buildContent(LoadState state) => switch (state) {
LoadStateLoading() => const CircularProgressIndicator(),
LoadStateData(:final items) => ItemList(items: items),
LoadStateError(:final message) => ErrorPanel(message: message),
};Here, ItemList and ErrorPanel represent widgets in your application. Keep the state model independent from widgets so it can be tested without a Flutter rendering test.
Exercise
What compile-time problem should occur after adding a LoadState.empty() constructor without updating describeState?
Show answer
Dart should report that the switch is not exhaustive, so the new state must be handled.