Sub topic 2
Modeling Immutable State with Equatable and copyWith
This chapter assumes Dart classes, null safety, generics, and Flutter widget basics. It also assumes that you know a Cubit emits states, but have not yet modeled a state with several fields.
A state object describes everything the UI needs to know at one moment. For example, a todo screen might need a loading status, a list of todos, and an error message. Keeping these values in one object makes each state change explicit.
Why state should be immutable
An immutable object cannot be changed after it is created. Instead of modifying an existing state, create a new state containing the changed values.
Immutability gives state changes a clear history:
- The Cubit has the current state.
- A method creates a copy with one changed field.
- The Cubit emits the new state.
- Widgets compare the old and new states and rebuild when needed.
Mutating a list inside a state is a common error. For example, state.todos.add('Read') changes the existing list without creating a new state. Prefer a new list, such as [...state.todos, 'Read'].
Equatable and value equality
Dart normally compares objects by identity. Two separately created objects with the same field values are still different objects. Equatable adds value equality. You list the fields that define the state in props.
| Field | Purpose |
|---|---|
| `status` | Describes the current operation |
| `todos` | Contains the displayed data |
| `errorMessage` | Describes a failed operation |
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];
}
void main() {
const initial = TodosState();
final loaded = initial.copyWith(
status: TodosStatus.success,
todos: ['Read documentation'],
);
print(loaded.status); // TodosStatus.success
print(loaded.todos); // [Read documentation]
}The final fields prevent reassignment. The const constructor allows compile-time constants when all values are constant. copyWith keeps unchanged fields and replaces only the values supplied by the caller.
The nullable copyWith trap
The simple copyWith above cannot clear errorMessage. Passing null means “use the existing value” because of errorMessage ?? this.errorMessage. This is often acceptable for a small state, but it becomes a bug when an old error must disappear.
You can solve this with a sentinel value, a separate clearError parameter, or a generated immutable-state package. Choose one convention and test it. The important rule is that each emitted state must fully describe the UI, rather than relying on hidden mutations.
Exercise
Why should a Cubit emit a new state instead of changing state.todos directly?
Show answer
A new state makes the change observable and preserves the previous state. Direct mutation can bypass equality checks and prevent the UI from rebuilding.