Sub topic 5
Immutable Data Models
This chapter assumes you know Dart classes, final fields and const constructors. It also assumes you have read the earlier chapters on view models and repositories. Here you will look closely at the model that the repository returns and the view model exposes. You will see why the model should never change after it is created, how to write one correctly, and which mistakes cause bugs.
Why models are immutable
A data model holds a fact about your app, such as one todo item. In MVVM, several layers share these objects. The repository creates them, the view model keeps them, and the view reads them. If any layer can edit a model in place, the others can't tell when it changed.
An immutable model avoids that problem. After construction, no field changes. To "edit" a model, you build a new one. This gives you three guarantees:
- Predictable state. The view reads
todo.doneand it keeps that value until the view model publishes a different object. - Safe sharing. The repository can hand the same instance to several view models without defensive copies.
- Detectable change. Replacing an object is something you can observe. Quietly editing one is not.
Anatomy of an immutable model
An immutable Dart model has four parts: final fields, a const constructor, a copyWith method for making changed copies, and value equality.
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}) =>
Todo(id: id, title: title ?? this.title, done: done ?? this.done);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Todo &&
other.id == id &&
other.title == title &&
other.done == done;
@override
int get hashCode => Object.hash(id, title, done);
@override
String toString() => 'Todo(id: $id, title: $title, done: $done)';
}
void main() {
const original = Todo(id: 1, title: 'Write the view model');
final finished = original.copyWith(done: true);
print(original.done); // false
print(finished.done); // true
print(original == finished); // false
print(original == original.copyWith()); // true
print(identical(original, finished)); // false
}The final keyword stops code from assigning to a field after construction. The const constructor lets you write const Todo(...) and lets Flutter reuse identical instances. copyWith takes optional named arguments. Each argument that you leave out falls back to the current value, so you only name what changes.
Why equality matters
By default, two Todo objects are equal only if they are the same instance. That default causes two problems:
- Tests such as
expect(vm.todos, [const Todo(id: 1, title: 'A')])fail, even when every field matches. Selectorandcontext.selectfrom theproviderpackage decide whether to rebuild by comparing old and new values with==. Without value equality, a freshly built but identical object looks like a change.
Whenever you override ==, override hashCode with the same fields. Two objects that are equal must produce the same hash code, or they will misbehave as keys in a Set or Map. Object.hash combines the fields for you.
Immutability is shallow
final protects the field, not the object behind it. A final List<Todo> can still be changed with add, removeAt and sort. If a model holds a collection, you must protect the collection too.
class Project {
Project({required this.name, required List<Todo> todos})
: todos = List.unmodifiable(todos);
final String name;
final List<Todo> todos;
}
void main() {
final source = [const Todo(id: 1, title: 'A')];
final project = Project(name: 'Demo', todos: source);
source.add(const Todo(id: 2, title: 'B'));
print(project.todos.length); // 1, the copy is unaffected
try {
project.todos.add(const Todo(id: 3, title: 'C'));
} on UnsupportedError catch (e) {
print('Blocked: $e');
}
}List.unmodifiable makes a copy that throws UnsupportedError on any change. It also protects the model from later edits to the original list. UnmodifiableListView is different. It is only a read-only window onto the original list, so changes to the source list still show through it.
The same rule applies to the view model in the earlier chapters. TodoListViewModel exposes List<Todo> get todos, and the repository returns List.unmodifiable(_todos). That is why a view cannot change the list by accident.
Updates replace objects
An update never edits a model. It replaces one. The chain below shows what happens when a user checks a box.
Inside the repository, InMemoryTodoRepository.setDone does the same thing at a small scale. It calls _todos[index].copyWith(done: done) and stores the result at the same index. The old Todo object is left untouched, and any code still holding it sees consistent data.
Where models come from
Models are plain Dart objects with no knowledge of widgets, ChangeNotifier or HTTP. A service returns raw data, usually JSON, and the repository turns it into models. A fromJson factory on the model is a common home for that conversion. It stays free of Flutter imports, so you can test it as plain Dart.
factory Todo.fromJson(Map<String, Object?> json) => Todo(
id: json['id']! as int,
title: json['title']! as String,
done: json['done'] as bool? ?? false,
);Put this factory inside the Todo class. Validate here, at the boundary where untrusted data enters. After that, the rest of the app can trust the types.
The nullable `copyWith` trap
copyWith has one well-known flaw. It uses null to mean "keep the current value", so you can't use it to set a nullable field back to null. Suppose a task has an optional due date:
class Task {
const Task({required this.title, this.dueDate});
final String title;
final DateTime? dueDate;
Task copyWith({String? title, DateTime? Function()? dueDate}) => Task(
title: title ?? this.title,
dueDate: dueDate != null ? dueDate() : this.dueDate,
);
}
void main() {
final task = Task(title: 'Ship', dueDate: DateTime(2026, 12, 1));
print(task.copyWith(title: 'Ship v2').dueDate); // kept
print(task.copyWith(dueDate: () => null).dueDate); // null, cleared
}The nullable field takes a function. Passing no function means "keep it". Passing () => null means "clear it". Generators such as freezed solve this for you, but it helps to know what they do.
Common mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Non-final fields, for example `bool done;` | Any layer can edit shared state without notifying anyone | Make every field `final` |
| Mutating the list in place, such as `_todos.add(t)` in the view model | `Selector` sees the same list instance and skips the rebuild | Assign a new list: `_todos = [..._todos, t]` |
| Exposing the private list directly | A view can change state with no notification | Expose `List.unmodifiable` or build a new list per update |
| Overriding `==` without `hashCode` | Wrong behavior in `Set`, `Map` keys and `distinct` checks | Always override both, using the same fields |
| Using `copyWith` to clear a nullable field | The field silently keeps its old value | Use the function-argument pattern above |
| Putting `notifyListeners` or Flutter imports in a model | The model can no longer be tested as plain Dart | Keep models free of framework code |
Writing less boilerplate
Hand-written ==, hashCode and copyWith grow tedious as fields increase. Three common options exist:
freezedorbuilt_value. These code generators produce equality,copyWith, and JSON support. They add a build step, but they remove an entire class of mistakes in larger models.- Dart records.
({int id, String title, bool done})has built-in value equality and is immutable. Records lack acopyWithand can't have methods, so they suit small, short-lived values better than central domain models. - Hand-written classes. For a handful of small models, as in this tutorial, writing them by hand is fine and keeps the code easy to follow.
Exercises
Exercise
A view model keeps final List<Todo> _todos = []; and adds items with _todos.add(todo); notifyListeners();. The screen updates correctly with ListenableBuilder, but a widget using context.select<TodoListViewModel, List<Todo>>((vm) => vm.todos) never rebuilds. Why, and how do you fix it?
Show answer
context.select compares the old and new selected values with ==. The view model mutates the same list instance in place, so the old and new values are the same object and compare as equal. ListenableBuilder doesn't compare anything, which is why it still works. Fix it by making _todos a non-final field and assigning a new list on each change, for example _todos = [..._todos, todo];, then calling notifyListeners().
Exercise
You add final DateTime? dueDate; to Todo and a plain DateTime? dueDate parameter to copyWith. A user removes a due date in the UI, and the view model calls todo.copyWith(dueDate: null). The old date remains. Why, and what change to copyWith fixes it?
Show answer
dueDate ?? this.dueDate treats null as "keep the current value", so passing null can't clear the field. Change the parameter type to DateTime? Function()?, and in the body use dueDate != null ? dueDate() : this.dueDate. Callers then clear the field with copyWith(dueDate: () => null).