Sub topic 1
Why Immutable Data Classes
A Flutter app is mostly a function from state to widgets. When the state is a plain object that any code can edit in place, it becomes hard to say what changed, when it changed, and who changed it. This chapter explains why immutable data classes fix that, what they cost, and where the freezed package fits in. Later chapters cover the package itself.
Prerequisites
This chapter assumes you already know:
- Dart classes, constructors, and named parameters.
- Null safety: nullable types (
String?) andrequiredparameters. - The basic structure of a Flutter app: widgets,
build, and the idea that a state change triggers a rebuild. - How to run Dart code from a terminal with
dart run. The examples below are plain Dart and need no Flutter SDK.
Dart 3 features such as sealed classes and switch expressions are not needed yet. They appear in later chapters.
What immutable means
An object is immutable if its fields cannot change after construction. In Dart you get this with final fields and, when possible, a const constructor.
class User {
const User({required this.name, required this.age});
final String name;
final int age;
}After const User(name: 'Ada', age: 36) exists, no code can assign user.age = 37. The compiler rejects it. To represent a different state, you create a new object.
A const constructor adds two things. The compiler can build the object at compile time. Identical const expressions also share one canonical instance. Neither is required for immutability, but both are free once every field is final.
The problem with mutable state
Flutter's change detection depends on comparing a previous value with a new one. setState, ValueNotifier, ChangeNotifier, and most state-management libraries decide whether to rebuild by asking whether the new value differs from the old one. If you edit an object in place, the old value and the new value are the same object, so there is nothing to compare.
The program below uses a small store that notifies listeners only when the value it holds is replaced. It mirrors how ValueNotifier behaves.
class Store<T> {
Store(this._state);
T _state;
final _listeners = <void Function(T)>[];
T get state => _state;
void listen(void Function(T) listener) => _listeners.add(listener);
void set(T next) {
if (identical(_state, next)) return; // nothing to compare, nothing to tell
_state = next;
for (final listener in _listeners) {
listener(next);
}
}
}
class MutableCounter {
int value = 0;
}
class Counter {
const Counter(this.value);
final int value;
}
void main() {
final bad = Store(MutableCounter());
bad.listen((_) => print('bad: notified'));
bad.state.value++; // edited in place
bad.set(bad.state); // same object, so no notification
print('bad value: ${bad.state.value}');
final good = Store(const Counter(0));
good.listen((c) => print('good: notified, ${c.value}'));
good.set(Counter(good.state.value + 1)); // a new object
}Running it prints:
bad value: 1
good: notified, 1The mutable store holds the right data, but no listener hears about it. In a real app this shows up as a screen that shows stale values until something unrelated forces a rebuild. The immutable version cannot have this bug, because the only way to change state is to produce a new object.
Updating without mutation
If objects never change, you need a convenient way to produce a slightly different copy. The standard answer is a copyWith method: it takes optional replacements for each field and fills the rest from the current object.
class User {
const User({required this.name, required this.age});
final String name;
final int age;
User copyWith({String? name, int? age}) =>
User(name: name ?? this.name, age: age ?? this.age);
}
void main() {
const ada = User(name: 'Ada', age: 36);
final older = ada.copyWith(age: 37);
print('${ada.age} -> ${older.age}'); // 36 -> 37
}This version has a known limit. With name ?? this.name, you cannot use copyWith to set a nullable field back to null, because null means "keep the current value". Hand-written copyWith methods usually get this wrong or work around it with sentinel objects. Generated code handles it consistently, which is one reason to generate it.
What you gain
| Benefit | Why it follows from immutability |
|---|---|
| Predictable change detection | A different object means a different state, so a cheap comparison is enough. |
| Safe sharing | Several widgets or layers can hold the same object. None of them can edit it behind the others' backs. |
| Easier debugging | You can log each state object and see the full sequence. Nothing rewrites earlier entries. |
| Undo and history | Keeping old states is a matter of keeping references to them. |
| Thread safety across isolates | An immutable object has no write races. (Isolates copy messages anyway, but the design carries over.) |
| Simpler tests | You construct an input, call a function, and compare an output. You do not inspect hidden mutations. |
Shallow immutability: the main edge case
final makes a field non-reassignable. It does not make the object the field refers to immutable. A final List<String> field still allows list.add(...).
class Playlist {
const Playlist(this.tracks);
final List<String> tracks;
}
void main() {
final tracks = ['a', 'b'];
final shared = Playlist(tracks);
tracks.add('c'); // the caller still holds the same list
print(shared.tracks.length); // 3: the "immutable" object changed
final safe = Playlist(List.unmodifiable(tracks)); // defensive copy
tracks.add('d');
print(safe.tracks.length); // 3: unaffected by the later add
try {
safe.tracks.add('x');
} on UnsupportedError {
print('blocked');
}
}The output is 3, 3, blocked.
The same applies to a field whose type is a mutable class. A class is only as immutable as everything it contains.
Equality: why immutability is not enough
Immutability tells you that an object will not change. It does not tell you whether two separate objects hold the same data. In Dart, == on a plain class compares identity, not contents.
class Point {
const Point(this.x, this.y);
final int x;
final int y;
}
void main() {
print(Point(1, 2) == Point(1, 2)); // false: two different objects
print(const Point(1, 2) == const Point(1, 2)); // true: one canonical constant
}The first comparison is false even though both points hold (1, 2). The second is true only because const canonicalizes identical constants. In real code, values usually come from JSON, user input, or computation at run time, so you cannot rely on const.
For state management this matters. If a store replaces Point(1, 2) with another Point(1, 2) and compares by identity, it sees a change and rebuilds the UI for nothing. To avoid that, you override == and hashCode so that equal fields mean equal objects. Together with toString and copyWith, that is the boilerplate the next chapter writes by hand and then replaces with generated code.
Costs and trade-offs
Immutable data is not free. Know the costs before adopting it everywhere.
- Allocation. Each update creates a new object. For small data classes the Dart garbage collector handles this well. For a large list of thousands of items rebuilt on every keystroke, it can matter. Measure before optimizing.
- Verbosity. Updating a deeply nested field means rebuilding every object on the path from the root. Generated nested
copyWithhelps, and a later chapter shows it. - Not everything should be immutable. Controllers, streams, and objects with identity and a lifecycle (a
TextEditingController, a database connection) are meant to change. Model data as immutable values and keep behavior holders mutable. - Code generation adds a build step. Generated files must be created and kept current. You trade hand-written boilerplate for a tool in your workflow.
Where freezed fits
Writing the immutable class, copyWith, ==, hashCode, and toString for every model is repetitive and easy to get wrong. A forgotten field in == produces a silent bug. The freezed package generates all of it from a short declaration. The same tooling can also produce JSON conversion and sealed unions for modeling states such as loading, data, and error.
The rest of this tutorial goes in this order: value equality and the boilerplate it needs, installing the tools, declaring your first freezed class, and then the features built on it.
Exercise
A Store holds a CartState object with a final List<String> items field. A developer calls store.state.items.add('milk') and then store.set(store.state). The UI does not update. Give two reasons the design allowed this, and one change that fixes each.
Show answer
First, the list inside the "immutable" class is mutable, because final only prevents reassigning the field. Fix: copy the list with List.unmodifiable when constructing the state, so add throws. Second, the update reuses the same object, so a store that compares old and new state sees no difference. Fix: build a new state, for example store.set(CartState([...store.state.items, 'milk'])), so the new object differs from the old one.
Exercise
Why does Point(1, 2) == Point(1, 2) return false for a plain class, and what must you add so it returns true?
Show answer
The default == compares object identity, and the two expressions create two separate objects. You must override == to compare the fields (x and y) and override hashCode with the same fields, for example Object.hash(x, y), so equal objects also have equal hash codes.