Sub topic 3
Installing freezed and running build_runner
This chapter assumes you can write Dart classes with named parameters, you know null safety, and you can run commands in a terminal inside a Flutter or Dart project. By the end you will have freezed installed, one class generating correctly, and a plan for the errors that code generation tends to produce.
What code generation changes in your workflow
freezed does not work at runtime. It is a code generator. You write a short class declaration with annotations, and a tool called build_runner writes the long Dart code (equality, hashCode, toString, copyWith) into separate files. Those files are compiled with your app like any other Dart source.
This has two consequences:
- Your editor shows errors on a new freezed class until you run the generator, because the generated file does not exist yet.
- When you change a freezed class, the generated files are out of date until you run the generator again.
Most freezed problems come from one of these two states, so keep them in mind.
The packages involved
freezed splits its work across several packages. Each has a different role and a different place in pubspec.yaml.
| Package | Section | Role |
|---|---|---|
| `freezed_annotation` | dependencies | Annotations such as `@freezed` and `@Default`. Your app imports it at runtime. |
| `json_annotation` | dependencies | Annotations such as `@JsonKey`. Needed only for JSON, but it is cheap to add now. |
| `build_runner` | dev_dependencies | The tool that runs code generators over your project. |
| `freezed` | dev_dependencies | The generator that writes `*.freezed.dart` files. |
| `json_serializable` | dev_dependencies | The generator that writes `*.g.dart` files with `fromJson` and `toJson`. |
The annotation packages go in dependencies because your source code imports them. The generators go in dev_dependencies because they run only on your machine or in CI and never ship in the app.
Installing the packages
Run these commands from the project root. They add the annotation packages as dependencies, add the generators as dev dependencies, and run the generator once.
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 add works the same way. Either command edits pubspec.yaml and resolves dependencies.
After the two pub add commands, the relevant parts of pubspec.yaml look like this. Your version numbers will differ, because pub add picks the latest versions compatible with your SDK.
dependencies:
flutter:
sdk: flutter
freezed_annotation: ^3.0.0
json_annotation: ^4.9.0
dev_dependencies:
build_runner: ^2.4.0
freezed: ^3.0.0
json_serializable: ^6.9.0The first build_runner build will print "Nothing to build" or generate nothing, because no class uses @freezed yet. That is expected.
How a source file maps to generated files
The generator reads each Dart file that contains a recognized annotation. It writes its output next to the source file, using the source file's name as a prefix. Your source file pulls the output in with part directives.
The naming rule is strict: for person.dart, the directives must be exactly part 'person.freezed.dart'; and, if you use JSON, part 'person.g.dart';. If the file name and the directive disagree, the generator cannot attach its output to your library and you get errors about missing members.
A minimal class to test the setup
Create lib/person.dart:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
@freezed
abstract class Person with _$Person {
const factory Person({
required String name,
@Default(0) int age,
}) = _Person;
}Before generation, your editor will underline _$Person and _Person as undefined. That confirms the generated file is missing. Now run the generator:
dart run build_runner build --delete-conflicting-outputsYou should see lib/person.freezed.dart appear, and the underlines should disappear. Add a small main to prove the class works:
import 'person.dart';
void main() {
const a = Person(name: 'Ada', age: 36);
const b = Person(name: 'Ada', age: 36);
print(a == b); // true
print(a.copyWith(age: 37)); // Person(name: Ada, age: 37)
}Equality comes back true even though a and b are separate declarations, because the generated class compares fields. The next chapters cover that code in detail. Here you only need to see that generation worked.
The three build_runner commands you will use
build
dart run build_runner build runs every generator once and exits. Use it in CI, before committing, and after pulling changes from others.
watch
dart run build_runner watch stays running and regenerates files whenever you save a source file. Most developers keep it open in a terminal during active model work. Add --delete-conflicting-outputs to it as well.
dart run build_runner watch --delete-conflicting-outputsclean
dart run build_runner clean deletes build_runner's cache. It does not delete your generated files in lib/. Use it when the generator seems to ignore your changes, then run build again.
What --delete-conflicting-outputs does
buildrunner records which files it generated. If a generated file already exists and buildrunner did not create it in its current cache state, it refuses to overwrite the file. This happens after you switch branches, delete the .dart_tool folder, or copy a project. The error mentions "conflicting outputs".
The --delete-conflicting-outputs flag tells build_runner to delete such files and write fresh ones. This is safe for generated files. It is not safe if you hand-edited a generated file, but you should never do that, since the next build overwrites your edit anyway.
Should generated files be committed?
Teams disagree, and both choices work. Weigh them:
| Choice | Benefit | Cost |
|---|---|---|
| Commit `*.freezed.dart` and `*.g.dart` | The project compiles right after `git clone`. CI needs no generation step. | Large diffs in pull requests. Merge conflicts in generated files. |
| Ignore them in `.gitignore` | Small diffs. No generated-file conflicts. | Everyone must run `build_runner` after clone. CI must run it before analysis and tests. |
If you ignore them, add these lines to .gitignore and add a generation step to CI:
*.freezed.dart
*.g.dartIf you commit them, run build before every commit that touches a model, so the committed generated code matches the source.
Common setup errors and what they mean
Missing part file
The error reads Target of URI doesn't exist: 'person.freezed.dart'. Either generation has not run yet, or the file failed to generate. Run build, and read the output for generator errors above the final summary.
Part directive missing or misspelled
Symptoms include _$Person being undefined even after a successful build. Check that the part directive exists and that its file name matches your source file exactly, including underscores and case.
Missing "with _$ClassName"
If the class declaration omits with _$Person, the generated mixin is never applied. The factory constructor then fails to compile, with messages about missing implementations.
Stale generated code
You renamed a field, but the old name appears in errors. The generated file is out of date. Run build again, or start watch so this happens automatically.
Version conflicts in dart pub
dart pub add may fail with a version solving error if your SDK constraint is too old for the latest freezed. Check your environment: sdk: constraint, or let pub suggest a compatible version.
Older tutorials do not compile
Older freezed code used @freezed class Person with _$Person, without abstract. Current freezed requires a class with only factory constructors to be marked abstract, and union types to be marked sealed. If you copy code from an old article and see errors about the class needing to be abstract or sealed, that is the cause.
A quick checklist before you move on
- The two annotation packages are in
dependencies, and the three generator packages are indev_dependencies. - Each freezed source file has a
partdirective that matches its file name. - Each freezed class has
with _$ClassName, and usesabstractorsealed. - You ran
dart run build_runner build --delete-conflicting-outputsafter your last change, orwatchis running. - You have decided whether generated files are committed or ignored, and your CI matches that decision.
Exercise
You rename the file lib/user.dart to lib/account.dart but leave part 'user.freezed.dart'; inside it. You then run dart run build_runner build --delete-conflicting-outputs. What goes wrong, and what is the fix?
Show answer
The generator writes its output to account.freezed.dart, since output names follow the source file name. The part 'user.freezed.dart'; directive points to a file that does not exist, so the compiler reports a missing part file and _$User style members stay undefined. The fix is to change the directive to part 'account.freezed.dart'; (and part 'account.g.dart'; if JSON is used) and run the build again. Delete the old user.freezed.dart if it is still there.
Exercise
Why are freezed and build_runner listed under dev_dependencies, while freezed_annotation is listed under dependencies?
Show answer
Your app code imports freezed_annotation for annotations like @freezed and @Default, so it must be available at runtime and in the built app. freezed and build_runner only run during development and CI to produce Dart files, so they are not needed in the shipped app.