Sub topic 2
Value equality and the boilerplate it requires
This chapter assumes you know Dart classes, constructors, named parameters, and null safety. You do not need freezed installed yet. By the end you will know what value equality is, why Flutter state depends on it, and exactly which methods you would have to write by hand without code generation.
Identity equality versus value equality
Dart has two ideas of "the same object".
- Identity equality asks whether two variables point to the same object in memory. The
identicalfunction tests this. - Value equality asks whether two objects hold the same data, even if they are different objects in memory.
A plain Dart class gets identity equality by default. The inherited == operator from Object is the same as identical.
class Person {
const Person({required this.name, required this.age});
final String name;
final int age;
}
void main() {
final a = Person(name: 'Ada', age: 36);
final b = Person(name: 'Ada', age: 36);
print(a == b); // false
print(identical(a, b)); // false
print(a == a); // true
}a and b carry identical data, yet a == b is false. They are two separate objects, and the default == only compares the objects themselves.
Some Dart types already use value equality. Strings, numbers, and booleans do. 'Ada' == 'Ada' is true. Records also compare by value. Collections do not: [1, 2] == [1, 2] is false for two separate lists.
Constant objects are a special case. Dart canonicalizes const instances with the same arguments, so they become the same object.
void main() {
const a = Person(name: 'Ada', age: 36);
const b = Person(name: 'Ada', age: 36);
print(identical(a, b)); // true
}This works only when you create the objects with const. Data that comes from JSON, a database, or user input is built at runtime, so it is never canonicalized. You cannot rely on const for value equality in real apps.
Why Flutter state needs value equality
Flutter decides what to rebuild by comparing old and new values. Several common mechanisms use == for that comparison.
ValueNotifiernotifies listeners only when the new value is not==to the old one.- Selectors in state libraries such as Provider and Riverpod skip rebuilds when the selected value is equal to the previous one.
Equatable-style state classes in Bloc rely on==to drop duplicate states.- Widget tests compare expected and actual models with
equals.
With identity equality, two copies of the same data look different. The framework rebuilds widgets for no reason, and tests fail even when the values match. If you do the opposite and mutate an object in place, the old and new values are the same object, so == says nothing changed and the UI never updates.
Immutability and value equality work as a pair. An immutable object cannot change after construction, so its value is fixed. That makes it safe to define equality by value. If an object could change after you put it in a Set or use it as a Map key, its hashCode would change and the collection would lose track of it.
The boilerplate for a correct value class
To get value equality you must override three members. They have to agree with each other. Add copyWith, which immutable classes need in order to be updated, and you have four.
class Person {
const Person({required this.name, required this.age});
final String name;
final int age;
Person copyWith({String? name, int? age}) =>
Person(name: name ?? this.name, age: age ?? this.age);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Person && other.name == name && other.age == age;
@override
int get hashCode => Object.hash(name, age);
@override
String toString() => 'Person(name: $name, age: $age)';
}Each piece has a job.
operator ==compares the fields. Theidenticalshortcut returns early when both sides are the same object. Theother is Personcheck handles both a wrong type andnull.hashCodemust produce the same number for any two objects that are==.Object.hashcombines the field hashes into one number. Hash-based collections such asSetandMapcallhashCodefirst.toStringprints the fields. Without it, logs and test failures showInstance of 'Person', which tells you nothing.copyWithbuilds a new object with some fields changed. It is how you "modify" an immutable value.
The ==/hashCode contract is the one that breaks silently. If two objects are equal, their hash codes must match.
Seeing it work
With the full class in place, equal data now compares equal, and a hash-based Set removes duplicates.
void main() {
final a = Person(name: 'Ada', age: 36);
final b = Person(name: 'Ada', age: 36);
print(a == b); // true
print(a.hashCode == b.hashCode); // true
print({a, b}.length); // 1
print(a.copyWith(age: 37)); // Person(name: Ada, age: 37)
print(a == a.copyWith(age: 37)); // false
}Where hand-written equality goes wrong
The class above is short because it has two fields. The cost grows with every field you add, and mistakes do not produce compile errors.
- A forgotten field. You add
emailto the class and the constructor but not to==. Two people with different emails now compare equal. - A
hashCodeout of sync with==. You add the field to==and forgethashCode. Equal objects may land in different hash buckets. - A stale
copyWith. You add a field and forget the parameter. The new field silently resets or cannot be changed. - A stale
toString. Debug output omits the new field, so logs mislead you. - Nullable fields in
copyWith. Thename ?? this.namepattern cannot set a nullable field tonull. Passingnullmeans "keep the old value".
The last problem deserves an example.
class Profile {
const Profile({required this.name, this.nickname});
final String name;
final String? nickname;
Profile copyWith({String? name, String? nickname}) =>
Profile(name: name ?? this.name, nickname: nickname ?? this.nickname);
}
void main() {
const p = Profile(name: 'Ada', nickname: 'Countess');
final cleared = p.copyWith(nickname: null);
print(cleared.nickname); // Countess, not null
}The caller asked to clear the nickname and nothing happened. Fixing this by hand needs a sentinel value or a wrapper type, which is more code to maintain.
Collections add another trap. Fields of type List or Map use identity equality, so two Person-like classes holding equal lists are not equal unless you compare the lists element by element. A correct hand-written version would use ListEquality from package:collection in both == and hashCode.
import 'package:collection/collection.dart';
class Team {
const Team({required this.name, required this.members});
final String name;
final List<String> members;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Team &&
other.name == name &&
const ListEquality<String>().equals(other.members, members);
@override
int get hashCode =>
Object.hash(name, const ListEquality<String>().hash(members));
}Now count the boilerplate. A model with eight fields needs eight entries in ==, eight in hashCode, eight in toString, and eight parameters in copyWith, all kept in sync by hand. A typical app has dozens of such models.
Options for reducing the boilerplate
| Approach | What you write | Limits |
|---|---|---|
| Hand-written class | All four members | Easy to leave out a field, grows with each field |
| `Equatable` package | A `props` list | Gives `==` and `hashCode` only, no `copyWith`, and fields are not enforced as `final` |
| Dart records | Nothing extra | Value equality for free, but no named type with methods, and no generated `copyWith` |
| `freezed` | An annotated class | Needs a code generation step |
Equatable removes the two riskiest methods, but you still maintain props by hand, and you still write copyWith and toString yourself. Freezed generates all four from the field list, so adding a field means adding one line to the constructor. The next chapters show how to install it and what it produces.
Summary of the key points
- Plain Dart classes compare by identity, so equal data in two objects is not
==. - Flutter rebuild checks, state libraries, and tests depend on
==, so models need value equality. - Value equality needs
==andhashCodethat agree, plustoStringandcopyWithfor a usable immutable class. - Hand-written versions fail silently when a field is added, and
copyWithcannot clear nullable fields with the simple pattern. - Generating the members from the field list removes that class of error.
Exercise
A teammate adds a String? email field to a hand-written Person class. They update the constructor and operator ==, but forget hashCode. What goes wrong, and what check would catch it?
Show answer
Two Person objects with equal fields now compare equal with ==, but they can have different hash codes. A Set<Person> may then keep both as separate entries, and a Map<Person, ...> lookup may fail to find a key that is equal. A test that creates two equal objects and asserts a.hashCode == b.hashCode, or that {a, b}.length == 1, would catch it.
Exercise
Given const Profile(name: 'Ada', nickname: 'Countess') and the hand-written copyWith using nickname ?? this.nickname, why does copyWith(nickname: null) leave the nickname unchanged, and why is that a problem for immutable state?
Show answer
In Dart, null ?? this.nickname evaluates to this.nickname, so passing null is indistinguishable from not passing the argument. The caller cannot clear a nullable field, so the state can never move back to "no nickname" through copyWith. Fixing it by hand needs a sentinel default value or a wrapper type.