Sub topic 4
Your first freezed class
This chapter builds one freezed class from an empty file to a working, generated model. It assumes you can read Dart classes with named parameters and null safety, and that you have a Dart or Flutter project where you can run terminal commands. The earlier chapters covered why immutability and value equality matter and how to install the packages. Here you write the declaration, run the generator, and learn what each line is for.
What you are going to write
A freezed class is a short declaration. You describe the fields, and the generator writes the long version: the constructor, the final fields, ==, hashCode, toString and copyWith.
Create lib/person.dart:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
@freezed
abstract class Person with _$Person {
@Assert('age >= 0')
const factory Person({
required String name,
@Default(0) int age,
String? nickname,
}) = _Person;
}At this point the file will not compile. It refers to _$Person and _Person, which do not exist until the generator runs. That is expected.
The anatomy, line by line
Each part of the declaration has one job, and most first-time errors come from leaving one out.
| Part | Purpose |
|---|---|
| `import '...freezed_annotation.dart'` | Provides `@freezed`, `@Default` and `@Assert`. It is a small runtime dependency. |
| `part 'person.freezed.dart';` | Tells Dart that the generated file is part of this library. The name must match your file name. |
| `@freezed` | Marks the class for the generator. |
| `abstract class Person` | Declares the public type. In freezed 3 and later, a non-union class must be `abstract` (or `sealed` for unions). |
| `with _$Person` | Mixes in the generated members: getters, `copyWith`, `==`, `hashCode` and `toString`. |
| `const factory Person(...) = _Person;` | A redirecting factory constructor. Its parameters define the fields. It redirects to the generated `_Person` class. |
The redirecting factory is the key idea. You never write final String name;. The parameter list is the single source of truth, and the generator turns each parameter into a final field on _Person.
Running the generator
If you have not yet installed the packages, this is the full setup:
dart pub add freezed_annotation json_annotation
dart pub add --dev build_runner freezed json_serializable
dart run build_runner build --delete-conflicting-outputsIn a Flutter project, flutter pub run build_runner build also works, but dart run is the current form. The --delete-conflicting-outputs flag removes stale generated files that would otherwise make the build fail.
While you edit models, you can keep the generator running:
dart run build_runner watch --delete-conflicting-outputsWatch mode regenerates files each time you save.
The diagram shows a loop. The generated file is a part of your file, so the two compile as one library. That is why the generated class _Person can be private, and why the names in the part line must match exactly.
What the generated file contains
Open person.freezed.dart once and skim it. You will see two main pieces.
- A mixin
_$Personthat declares the getters (name,age,nickname), acopyWithgetter, and the abstract equality contract. - A class
_Personthat implementsPerson, holds thefinalfields, and overrides==,hashCodeandtoString.
Compare this with the hand-written Person class from the earlier chapter. The generated code does the same job, including Object.hash over the fields and a copyWith that falls back to the existing value. Do not edit the generated file. The next build overwrites your edits.
Using the class
Now the constructor is available, and the class behaves as an immutable value:
void main() {
const ada = Person(name: 'Ada', age: 36);
final older = ada.copyWith(age: 37);
print(ada == older); // false
print(older); // Person(name: Ada, age: 37, nickname: null)
print(ada == const Person(name: 'Ada', age: 36)); // true
print(ada.nickname); // null
}Three things are worth noticing.
adaisconst. The factory is declaredconst, so any call with constant arguments can be a compile-time constant.copyWithreturns a new object.adais unchanged, and no setter exists. Writingada.age = 40is a compile error.- The last comparison is
trueeven though the two objects were created separately. Equality compares field values, not identity.
Required, default and optional fields
The three field styles in the declaration map to the three parameter styles in Dart.
required String namehas no default and cannot be omitted. The compiler enforces it at every call site.@Default(0) int agemakes the parameter optional and uses0when it is missing. The default must be a constant expression. Freezed uses the annotation instead of= 0because the redirecting factory needs the default to be copied into the generated class.String? nicknameis nullable and implicitly defaults tonull. You do not needrequired.
So Person(name: 'Grace') is valid and gives age 0 and nickname null.
Assertions
@Assert('age >= 0') adds an assert to the generated constructor. The string is Dart source that the generator pastes into the constructor, so it can refer to any field by name.
void main() {
// Throws an AssertionError in debug mode and in tests.
Person(name: 'Ada', age: -1);
}Asserts run only in debug mode and tests. In a release build they are stripped, so an assertion documents and checks developer mistakes, but it is not input validation for user data. Validate untrusted input explicitly, for example with a method that returns an error.
Because const Person(name: 'Ada', age: -1) is evaluated at compile time, the compiler reports the failed assert as an error instead of a runtime exception.
Common errors and what they mean
Most messages in the first hour come from a short list.
| Symptom | Cause | Fix |
|---|---|---|
| `Undefined name '_$Person'` or `_Person` | The generator has not run, or failed. | Run `dart run build_runner build --delete-conflicting-outputs`. |
| `Missing "part" directive` warning from the generator, or no file produced | The `part 'person.freezed.dart';` line is missing or misspelled. | Match the file name exactly, including the `.freezed.dart` suffix. |
| `The non-abstract class '_Person' is missing implementations` or a message about `abstract` | You omitted `abstract` (or `sealed`) on a freezed 3 class. | Add `abstract class Person with _$Person`. |
| `Missing concrete implementation` for `copyWith` | `with _$Person` is missing. | Add the mixin to the class declaration. |
| New field not visible after editing | The generated file is stale. | Rerun the build, or use `watch`. |
| Conflicting outputs error | Old generated files remain from a previous run. | Add `--delete-conflicting-outputs`. |
If an error persists after a rebuild, scroll up in the build output. The first error is usually the real one, and later errors cascade from it.
Should the generated files be committed?
Teams differ. Committing *.freezed.dart files means a fresh checkout builds without a generator step and makes code review show the generated change. Ignoring them keeps diffs small but requires every developer and every CI job to run build_runner. Whichever you choose, apply it to the whole project so that a missing file is never a surprise. In CI, a good check is to run the build and then fail if git diff is not empty, which catches stale committed output.
Checking your understanding
Try the declaration yourself. Add a field String? email to Person, rerun the generator, and confirm that Person(name: 'Ada').copyWith(email: '[email protected]') compiles. If it does not, work through the error table above.
Exercise
You add part 'person.freezed.dart'; and a @freezed class Person, then run the build, but the compiler still reports that _$Person is undefined. The class reads class Person with _$Person { const factory Person({required String name}) = _Person; }. Name two likely problems and how to check each.
Show answer
First, the class is missing the abstract keyword required by freezed 3, so the generator may report an error or skip the class. Check the buildrunner output for a message and change the declaration to `abstract class Person with $Person. Second, the generator may not have produced person.freezed.dart at all, because the build failed or was never run, or because the part file name does not match the Dart file name. Check that the generated file exists next to person.dart, and rerun dart run build_runner build --delete-conflicting-outputs`, reading the first error in the output.
Exercise
Why does freezed use @Default(0) int age instead of int age = 0 in the factory constructor, and why does an @Assert('age >= 0') not protect a release build?
Show answer
The generator needs the default as an annotation so it can copy the value into the generated _Person constructor that the factory redirects to. Asserts are compiled out of release builds, so the check only runs in debug mode and tests. It catches programming mistakes but does not validate user input at runtime in production.