Sub topic 5
Immutable Data Models
This chapter assumes that you know Dart classes, named parameters, null safety, and basic Flutter widget code. You should also understand that a final variable can be assigned once, but an object stored in that variable may still be mutable.
Why immutability matters in MVVM
In MVVM, the view model exposes state to the view. The view should be able to read that state without changing it directly. An immutable model helps enforce this boundary.
An immutable object cannot change after it is created. Instead of modifying an existing object, you create a new object containing the changed values. This makes state changes explicit and easier to reason about.
For example, a todo can be represented by an immutable Todo model:
class Todo {
const Todo({
required this.id,
required this.title,
this.done = false,
});
final int id;
final String title;
final bool done;
Todo copyWith({
String? title,
bool? done,
}) {
return Todo(
id: id,
title: title ?? this.title,
done: done ?? this.done,
);
}
@override
String toString() {
return 'Todo(id: $id, title: $title, done: $done)';
}
}
void main() {
const todo = Todo(id: 1, title: 'Read the chapter');
final completedTodo = todo.copyWith(done: true);
print(todo);
print(completedTodo);
}The final fields prevent reassignment after construction. The const constructor also allows compile-time constants when every argument is constant.
The copyWith method creates a new Todo. Passing done: true changes only that field. The original todo remains unchanged.
| Operation | Result |
|---|---|
| `todo.done` | Reads the current completion state |
| `todo.copyWith(done: true)` | Creates a new completed todo |
| `todo.done = true` | Compile-time error |
Models and view-model state
A view model can replace its list with a new list after an operation:
class TodoState {
const TodoState({required this.todos});
final List<Todo> todos;
TodoState copyWith({List<Todo>? todos}) {
return TodoState(todos: todos ?? this.todos);
}
}The list itself should also be protected from accidental modification. A view model can store an unmodifiable list, or return a read-only view of its internal collection. The exact approach depends on the state-management library, but the rule is the same: widgets read state and send actions back to the view model.
Common model mistakes
Avoid public mutable fields such as bool done without final. Also avoid changing a model inside a widget. That puts business logic in the UI and makes later testing harder.
When a model contains nested objects or collections, check whether those nested values are mutable. An immutable outer class does not automatically make its entire object graph immutable.
Exercise
What does todo.copyWith(done: true) return, and what happens to the original todo?
Show answer
It returns a new Todo with done set to true. The original Todo remains unchanged.