Sub topic 7
Reusing one state type for different data
This chapter assumes you know Dart classes, constructors and final fields, basic generics such as List<String>, and the Dart 3 sealed class syntax from the earlier chapters. It also assumes you have seen Loading, Loaded and Failed and a switch expression over them.
The duplication problem
A real app loads many kinds of data: a user profile, a list of products, a single order. If you model state per feature, you end up with this:
sealed class UserState {}
final class UserLoading extends UserState {}
final class UserLoaded extends UserState { UserLoaded(this.user); final User user; }
final class UserFailed extends UserState { UserFailed(this.error); final Object error; }
sealed class ProductsState {}
final class ProductsLoading extends ProductsState {}
final class ProductsLoaded extends ProductsState { ProductsLoaded(this.products); final List<Product> products; }
final class ProductsFailed extends ProductsState { ProductsFailed(this.error); final Object error; }The two hierarchies have the same shape. Only the type of the loaded data differs. Every new feature copies six more classes, and every fix (say, adding a stack trace to the failure case) must be made in each copy.
A type parameter fixes this. The shape is written once, and each feature chooses the data type it carries.
Adding a type parameter to the hierarchy
Put <T> on the sealed base class and on every subclass. Each subclass passes its T to the superclass.
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 User {
const User(this.name);
final String name;
}
String describeUser(LoadState<User> state) => switch (state) {
Loading() => 'Loading user...',
Loaded(data: final user) => 'Hello, ${user.name}',
Failed(error: final e) => 'Error: $e',
};
void main() {
print(describeUser(const Loading<User>()));
print(describeUser(const Loaded(User('Ada'))));
print(describeUser(Failed<User>(StateError('offline'))));
}Running this prints three lines: Loading user..., Hello, Ada and Error: Bad state: offline.
Three details matter here.
Loaded(User('Ada'))needs no explicit type argument. Dart infersTfrom the constructor argument, and the expected parameter typeLoadState<User>agrees.LoadingandFaileddo not useTin any field. They still declare it, so thatLoading<User>is aLoadState<User>and not aLoadState<Object?>. WithoutTon the subclass, the switch above would not type-check againstLoadState<User>.- The patterns
Loading()andFailed(error: ...)omit the type argument. The pattern takes it from the matched value's static type, so you rarely write it.
How patterns see the type argument
Inside a switch on LoadState<User>, the pattern Loaded(data: final user) binds user with type User. You do not need a cast. In LoadState<List<Product>>, the same pattern binds a List<Product>.
Exhaustiveness checking also works per instantiation. The compiler sees that Loading<User>, Loaded<User> and Failed<User> are the only subtypes of LoadState<User>. If you leave one out, you get a compile error, exactly as in the non-generic version.
Writing code that is generic itself
Once the state is generic, you can write helpers and widgets that work for any T. The first is a function that transforms the loaded data and passes the other states through:
LoadState<R> mapData<T, R>(LoadState<T> state, R Function(T) transform) =>
switch (state) {
Loading() => const Loading(),
Loaded(data: final d) => Loaded(transform(d)),
Failed(error: final e) => Failed(e),
};The return type LoadState<R> is the context that tells Dart which R to use for const Loading() and Failed(e). Each arm infers its own type argument from it. You can use the function like this:
final LoadState<User> userState = Loaded(const User('Ada'));
final LoadState<String> nameState = mapData(userState, (u) => u.name);The second helper is a widget that handles loading and error screens for any data type. The caller supplies only the widget for the loaded case:
import 'package:flutter/material.dart';
class LoadStateView<T> extends StatelessWidget {
const LoadStateView({super.key, required this.state, required this.builder});
final LoadState<T> state;
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: Text('Something went wrong: $e')),
};
}
}This block depends on the LoadState classes above, so keep them in the same library or import them. A screen then uses it like this:
LoadStateView<User>(
state: userState,
builder: (context, user) => Text(user.name),
)Every screen in the app now shows loading and failure the same way, and a design change happens in one place.
Choosing what T should be
T is the type of the successful result, so choose it to describe what the screen needs. The options differ in how much they let the compiler help you:
| Choice | Example | Effect |
|---|---|---|
| A domain type | `LoadState<User>` | The compiler knows exactly what `data` is. This is the default choice. |
| A collection | `LoadState<List<Product>>` | One state covers the whole list. You decide separately how to show an empty list (see the `when` chapter). |
| A nullable type | `LoadState<User?>` | `Loaded(null)` means "loaded, and there is no user." It is distinct from `Loading`. Use it only when absence is a valid result. |
| `dynamic` or `Object?` | `LoadState<dynamic>` | Patterns bind `data` as `dynamic`, so the compiler cannot check how you use it. Avoid it. |
Common errors
Missing context for inference. A constant with no context cannot infer T:
var state = const Loading(); // T cannot be inferred from anything
LoadState<User> state2 = const Loading(); // T is inferred as User
final state3 = const Loading<User>(); // T is written explicitlyIn the first line, state gets a type such as Loading<dynamic>. That type does not fit later uses where a LoadState<User> is required. Give the variable a declared type, or write the type argument.
Forgetting <T> on a subclass. If you write final class Loading extends LoadState<Object?>, then Loading is a LoadState<Object?> only. It is not a LoadState<User>, because the type argument is fixed. Your LoadState<User> values can no longer be Loading, and the switch above will not accept it as a variant. Keep <T> on every subclass unless you have a reason to do otherwise.
Mixing up state and data types. Loaded<List<String>> holds a list. LoadState<List<String>> is the state of loading that list. A parameter that should accept any state needs LoadState<T>, not T.
An untyped error. In these examples error is an Object. If you want to match on error kinds, you can add a second type parameter, Failed<T, E>, but then every LoadState needs it as well. Most apps keep Object and test the error with a nested pattern such as Failed(error: final SocketException e).
Summary of the design
- One generic sealed class replaces many copies of the same three states.
- Each subclass declares
<T>and passes it to the superclass, even when it does not store aT. - Patterns bind fields with the right static type, and exhaustiveness checking still works for each instantiation.
- Generic helpers such as
mapDataandLoadStateView<T>remove repeated code from the transformation and UI layers.
Exercise
A teammate writes final class Failed extends LoadState<Never> and final class Loading extends LoadState<Never>, but declares Loaded<T> as in this chapter. Without running the code, name one thing you would check about whether switch (state) on a LoadState<User> still compiles and is exhaustive, and describe how you would add a mapData helper that works with that design.
Show answer
Check that Loading and Failed are still subtypes of LoadState<User>. Dart generics are covariant and Never is a subtype of every type, so LoadState<Never> is a subtype of LoadState<User>, and the subclasses are accepted and counted by exhaustiveness checking. Confirm this by compiling a switch that omits each variant in turn and reading the errors. mapData can stay as written, because its Loading() and Failed(e) arms return values that are also valid LoadState<R> values. The simpler, more conventional design in this chapter, with <T> on every subclass, avoids relying on this reasoning.
Exercise
Write a generic function T valueOr<T>(LoadState<T> state, T fallback) that returns the loaded data, or fallback for the other two states.
Show answer
T valueOr<T>(LoadState<T> state, T fallback) => switch (state) { Loaded(data: final d) => d, Loading() || Failed() => fallback, };