Sub topic 5
What freezed generates for you
This chapter covers what freezed writes into the .freezed.dart file, how each generated member behaves, and the edge cases that surprise people. It assumes you have a project set up with freezed, freezed_annotation and build_runner, and that you have declared a first freezed class. It also assumes you know Dart named parameters and null safety.
Where the generated code lives
When you run dart run build_runner build, freezed reads your annotated class and writes a sibling file named <file>.freezed.dart. Your source file links to it with a part directive. A part file is compiled as if it were pasted into the file that declares it, which is why the generated code can reach private names such as _Profile.
The generated file has two main parts:
- The mixin
_$Profile. Your class applies it withwith _$Profile. It declares the fields as abstract getters and holds thecopyWithgetter. - The implementation class
_Profile. The factory constructor= _Profile;points at it. It holds the real final fields, the constructor, and thetoString,==andhashCodeoverrides.
Your public Profile is a thin abstract shell. The const factory redirects to _Profile, so Profile(...) returns a _Profile instance.
One class, four generated behaviors
The class below is the running example.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'profile.freezed.dart';
@freezed
abstract class Profile with _$Profile {
const factory Profile({
required String name,
String? nickname,
@Default(<String>[]) List<String> tags,
}) = _Profile;
}
void main() {
const ada = Profile(name: 'Ada', nickname: 'Countess');
// toString lists every field.
print(ada); // Profile(name: Ada, nickname: Countess, tags: [])
// copyWith can set a nullable field to null.
final anonymous = ada.copyWith(nickname: null);
print(anonymous); // Profile(name: Ada, nickname: null, tags: [])
print(ada == anonymous); // false
// Equality compares contents, not identity.
final a = Profile(name: 'Ada', tags: ['math']);
final b = Profile(name: 'Ada', tags: ['math']);
print(identical(a, b)); // false
print(a == b); // true
print(a.hashCode == b.hashCode); // true
}Save it as profile.dart and run the generator before running the file. Without profile.freezed.dart, the analyzer reports that _$Profile and _Profile are undefined.
toString
The generated toString prints the class name, then every field as name: value, in declaration order. The format is the same for every freezed class, so logs and test failure messages stay readable without extra work.
toString is only as useful as your field types. A field holding a plain class without its own toString prints as Instance of 'Foo'. If that field is itself a freezed class, its generated toString is used, and the output nests.
Equality and hashCode
The generated == returns true when all of these hold:
- The other object has the same runtime type. Two freezed classes with identical fields but different names are never equal.
- Every field is equal. Each field is compared with
==, with a shortcut when the two references are identical.
The generated hashCode combines the runtime type and all fields, using Object.hash. Because equal objects produce equal hash codes, freezed instances work as Set members and Map keys, and as values compared by widget and state-management code that checks "did the state change?".
Collection fields compare by contents
Dart's List, Map and Set use identity equality. [1] == [1] is false. If freezed used plain == on those fields, two models holding equal lists would not be equal. To avoid that, the generated code compares collection fields with DeepCollectionEquality from the collection package. That is why a == b printed true above even though the two lists are different objects.
Deep comparison also applies to nested collections, such as a Map<String, List<int>>. It does not make the collections themselves immutable. See the next section.
Unmodifiable collections by default
With default settings, freezed also wraps list, map and set fields in unmodifiable views, so the model cannot be changed through its own collection:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'cart.freezed.dart';
@freezed
abstract class Cart with _$Cart {
const factory Cart({required List<String> items}) = _Cart;
}
void main() {
final source = ['apple'];
final cart = Cart(items: source);
try {
cart.items.add('pear');
} on UnsupportedError {
print('cannot modify cart.items');
}
source.add('pear'); // The wrapper is a view of the original list.
print(cart.items); // Likely [apple, pear] in many versions
}The view protects callers from cart.items.add(...), but it still points at the list you passed in. If you keep a reference to source and mutate it, the model can change underneath you. Copy at the boundary with List.of(source) or List.unmodifiable(source) when you do not control the incoming list.
Behavior around collection wrapping has varied between freezed versions and can be switched off. If the exact behavior matters to you, check the changelog for the version in your pubspec.lock and look at the generated file.
copyWith
copyWith creates a new instance with some fields replaced and the rest copied from the original. It is how you "change" an immutable object.
final updated = ada.copyWith(tags: ['math', 'poetry']);Setting a nullable field to null
A common hand-written version is name ?? this.name. That form cannot distinguish "leave this field alone" from "set this field to null", so copyWith(nickname: null) leaves the old value in place.
Freezed's generated copyWith uses an internal sentinel default for each parameter. Omitting a parameter keeps the current value, and passing null explicitly sets a nullable field to null. In the example, ada.copyWith(nickname: null) produced nickname: null.
This only works for fields declared nullable. A required String name field is typed non-nullable in copyWith, so passing null is a compile-time error.
copyWith is an object
The copyWith member is a getter that returns a helper object, not an ordinary method. The helper is callable, so ada.copyWith(age: 1) reads like a method call. For fields that are themselves freezed classes, the helper also exposes a nested form, such as user.copyWith.address(city: 'Oslo'). That is covered in the chapter on nested objects.
One consequence: you can tear off or pass copyWith around less freely than a normal method, because it is a getter plus a call. Wrap it in a closure when you need a function value:
final rename = (Profile p) => p.copyWith(name: 'Grace');What is not generated
The generator does not add these members, so do not assume them:
- Setters. All fields are final.
compareToor ordering. ImplementComparableyourself if you need sorting.- JSON methods. Those come from
json_serializable, which runs only when you add afromJsonfactory and the.g.dartpart. See the JSON chapter. - Validation.
@Assertadds constructor assertions that run in debug mode. Release builds skip them.
Reading the generated file
Open profile.freezed.dart once. You will see the _$Profile mixin, the $ProfileCopyWith helper classes, and the _Profile class with ==, hashCode and toString. Treat it as read-only. Edits are overwritten on the next build, and a hand-edit can hide the real cause of a bug.
A few habits keep it from becoming a nuisance:
- Keep
--delete-conflicting-outputson your build command so stale files do not block a rebuild. - Use
dart run build_runner watchwhile editing models. - Decide as a team whether to commit generated files. Either choice works. Mixing the two causes confusing diffs and missing-file errors in CI.
Summary table
| Member | Generated into | Behavior |
|---|---|---|
| `toString` | `_Profile` | Prints `Profile(field: value, ...)` for every field |
| `==` | `_Profile` | Same runtime type and equal fields; collections compared by contents |
| `hashCode` | `_Profile` | `Object.hash` over runtime type and fields |
| `copyWith` | `_$Profile` mixin and helper classes | New instance; omitted fields kept; nullable fields can be set to null |
| Final fields and constructor | `_Profile` | Backing storage for the factory parameters |
Exercise
A model has the field String? nickname. A teammate calls profile.copyWith(nickname: null) on a freezed class and on a hand-written class whose copyWith uses nickname: nickname ?? this.nickname. What does each version return for the nickname, and why?
Show answer
The freezed version returns a profile with nickname: null, because its generated copyWith uses a sentinel default and can tell "omitted" from "explicit null". The hand-written version keeps the old nickname, because null ?? this.nickname falls back to the existing value. The ?? form cannot clear a nullable field.
Exercise
Two Profile objects are created with Profile(name: 'Ada', tags: ['math']). identical(a, b) is false, but a == b is true. Which generated behavior explains a == b, and which package supplies the collection comparison?
Show answer
The generated == compares every field instead of using reference identity. For the tags list it uses DeepCollectionEquality from the collection package, which compares elements, so equal lists count as equal even though they are different objects.