Sub topic 2
Modeling immutable state with Equatable and copyWith
This chapter assumes you know Dart classes, const constructors, null safety, and the difference between == and identical. You don't need any Bloc code yet. Everything here is plain Dart plus the equatable package, and the next chapters build Cubits on top of it.
Why state objects must be immutable
A Cubit or Bloc holds one state object at a time and announces changes by emitting a new one. The library decides whether anything changed by comparing the new state with the current one using ==. That design gives you two requirements:
- State is never edited in place. You build a new object for every change. If you mutate the old one, the old and new values are the same object, and the library sees no change.
- Two states with the same contents are equal. Dart's default
==compares object identity, so two separately built instances are never equal, even with identical fields.
The second point is easy to see:
class Point {
const Point(this.x);
final int x;
}
void main() {
print(const Point(1) == Point(1)); // false: different instances
}Equatable fixes this by overriding == and hashCode for you, based on a list of fields you declare.
A state class with Equatable
Add equatable to pubspec.yaml (for example dart pub add equatable). A state class has final fields, a const constructor with defaults, a copyWith method, and a props getter.
import 'package:equatable/equatable.dart';
enum TodosStatus { initial, loading, success, failure }
class TodosState extends Equatable {
const TodosState({
this.status = TodosStatus.initial,
this.todos = const [],
this.errorMessage,
});
final TodosStatus status;
final List<String> todos;
final String? errorMessage;
TodosState copyWith({
TodosStatus? status,
List<String>? todos,
String? errorMessage,
}) {
return TodosState(
status: status ?? this.status,
todos: todos ?? this.todos,
errorMessage: errorMessage ?? this.errorMessage,
);
}
@override
List<Object?> get props => [status, todos, errorMessage];
}Each part has a job:
finalfields stop reassignment after construction.- Default values in the constructor define the initial state, so
const TodosState()is the starting point for a Cubit. copyWithis how you "change" state. It returns a new instance that keeps every field you don't pass.propslists the fields that take part in equality. Equatable compares them in order.
You can check the behavior by adding this to the same file:
void main() {
const initial = TodosState();
final loading = initial.copyWith(status: TodosStatus.loading);
print(initial == loading); // false: status differs
print(initial == const TodosState()); // true: same values
print(initial.copyWith() == initial); // true: a copy with no changes
print(initial.hashCode == const TodosState().hashCode); // true
}How Bloc uses equality
When you call emit(newState), the library compares newState with the current state. If they are equal, and the Cubit has already emitted a state, the call is ignored. Listeners are not notified, and BlocBuilder does not rebuild. The first emission after construction is always allowed.
This is why Equatable matters beyond tidiness. Without value equality, every emit of a logically identical state would count as a change and trigger a rebuild. With it, redundant emits cost almost nothing.
Gotcha: mutating a list in place
Equatable compares collections by their contents, not by reference. That is useful, but it hides a trap. If you mutate the list that already lives inside the current state and emit that same state, the new and old state are the same object. They are equal, so the emit is dropped and the UI never updates.
import 'package:equatable/equatable.dart';
class ListState extends Equatable {
const ListState(this.items);
final List<String> items;
@override
List<Object?> get props => [items];
}
void main() {
final first = ListState(['a']);
// Wrong: the same list object is edited, so nothing new exists.
first.items.add('b');
print(first == ListState(first.items)); // true, no change detected
// Right: build a new list and a new state.
final second = ListState([...first.items, 'c']);
print(first == second); // false
}In a Cubit, write emit(state.copyWith(todos: [...state.todos, newTodo])). Never write state.todos.add(newTodo). The final keyword only protects the reference, not the list behind it.
Gotcha: copyWith cannot clear a nullable field
Look again at the errorMessage line in copyWith:
errorMessage: errorMessage ?? this.errorMessage,The ?? operator treats an explicit null the same as "not passed". So after a failure, calling state.copyWith(status: TodosStatus.success) keeps the old error message. Passing errorMessage: null doesn't help, because the result is identical.
This matters in practice. A stale errorMessage can show an error banner next to successfully loaded data, or make a BlocListener re-show a message.
You have three common fixes.
Option 1: Clear it by hand where it matters. Build a fresh state with the constructor instead of copyWith:
emit(TodosState(status: TodosStatus.success, todos: todos));This resets errorMessage to null, but it also resets any other field you forget to pass.
Option 2: Make the nullable parameter a function. The caller can then distinguish "leave it alone" (parameter omitted) from "set it to null" (a function returning null):
TodosState copyWith({
TodosStatus? status,
List<String>? todos,
String? Function()? errorMessage,
}) {
return TodosState(
status: status ?? this.status,
todos: todos ?? this.todos,
errorMessage: errorMessage != null ? errorMessage() : this.errorMessage,
);
}
// Set a message:
// state.copyWith(status: TodosStatus.failure, errorMessage: () => 'Offline');
// Clear it:
// state.copyWith(status: TodosStatus.success, errorMessage: () => null);Option 3: Clear it implicitly in the transition. Pass errorMessage: null through a constructor-based reset whenever the status moves to loading or success. The next chapters on asynchronous state show how a sealed-class design removes the problem entirely, since an error message only exists inside the failure state.
The table compares them.
| Approach | Strength | Weakness |
|---|---|---|
| Plain `??` copyWith | Shortest to write | Cannot reset a field to `null` |
| Constructor reset | No extra machinery | Easy to drop other fields by accident |
| `String? Function()?` parameter | Explicit, works for any nullable field | Slightly unusual call syntax |
Keeping props complete
Equality is only as good as props. If you add a field and forget to list it, two states that differ in that field compare as equal. The symptom is a UI that doesn't rebuild after a change you can see happening in the debugger.
A short checklist when you add a field:
- Add the
finalfield. - Add it to the constructor, with a default if it makes sense.
- Add it to
copyWith, both as a parameter and in the returned constructor call. - Add it to
props.
Design guidelines
- Keep state small and serializable in spirit. Store data the UI needs to draw itself, not widgets, controllers, or
BuildContext. - Use enums or sealed classes for modes. A
statusenum is clearer than several booleans likeisLoadingandhasError, which can contradict each other. - Prefer
constconstructors.const TodosState()allows the Cubit's initial state to be a compile-time constant. - Don't put derived values in
props. If a getter such asbool get isEmpty => todos.isEmptyis computed from fields, leave it out. It adds nothing to equality.
Exercise
A Cubit method runs state.todos.add('Buy milk'); emit(state);. The list now holds the new item, but the screen does not update. Why, and what is the fix?
Show answer
The list is mutated in place, so emit(state) passes the same object that is already the current state. Equatable equality sees it as equal to itself, and Bloc ignores the emit, so no rebuild happens. Build a new list and a new state instead: emit(state.copyWith(todos: [...state.todos, 'Buy milk']));.
Exercise
After a failed load, state.copyWith(status: TodosStatus.success, todos: todos) still shows the old error message. What causes this, and how does the String? Function()? parameter solve it?
Show answer
The line errorMessage ?? this.errorMessage cannot tell "not passed" from "passed null", so the old message is always kept. With a function parameter, omitting it keeps the current value, while passing errorMessage: () => null explicitly sets the field to null.
Exercise
You add a bool isRefreshing field to a state class, add it to the constructor and copyWith, but forget props. What bug will you see?
Show answer
Two states that differ only in isRefreshing compare as equal, so emit drops the change and BlocBuilder does not rebuild. The fix is to add isRefreshing to the props list.