Sub topic 3
Adding json_annotation, json_serializable, and build_runner
This chapter assumes you can read a pubspec.yaml, know what a Dart part file is at a basic level, and have worked through the previous chapters on dart:convert and manual serialization. You will add the three packages that make up the code-generation toolchain, check that they resolve correctly, and learn the failures that most often appear at this step. Writing the annotated model and running the generator in earnest come in the next two chapters.
Why three packages
Generated serialization needs three separate pieces. They are split because they run at different times.
| Package | Role | Where it goes | Runs |
|---|---|---|---|
| `json_annotation` | Defines the annotations (`@JsonSerializable`, `@JsonKey`, `@JsonValue`) and the `JsonConverter` interface | `dependencies` | In your app, at runtime |
| `json_serializable` | The generator. It reads your annotated classes and writes the `fromJson`/`toJson` code | `dev_dependencies` | At build time only |
| `build_runner` | The tool that discovers generators, runs them, and writes the output files | `dev_dependencies` | At build time only |
The reasoning follows from what ends up in your shipped app:
- Your model files import
json_annotationand use its annotations. The generated.g.dartfiles also import it. Both are compiled into the app, so it must be a regular dependency. json_serializableandbuild_runnerpull in the Dart analyzer and many other packages. Your app never calls them. Keeping them indev_dependenciesmeans they are never part of the app's dependency set.
Adding the packages
Run these two commands from the project root:
flutter pub add json_annotation
flutter pub add dev:build_runner dev:json_serializableThe first command adds json_annotation under dependencies. The dev: prefix in the second command puts the other two under dev_dependencies. Each command also runs flutter pub get, so the packages are downloaded and pubspec.lock is updated.
Your pubspec.yaml should now contain entries like these. The version numbers will differ, because pub add picks the newest versions compatible with your SDK and other packages.
dependencies:
flutter:
sdk: flutter
json_annotation: ^4.9.0
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^2.4.13
json_serializable: ^6.9.0The ^ prefix is a caret constraint. ^4.9.0 allows any version from 4.9.0 up to, but not including, 5.0.0. You do not need to match the numbers above. You only need the three packages to be in the right sections.
If you prefer to edit pubspec.yaml by hand, add the lines yourself and run flutter pub get. The result is the same.
Checking what was resolved
Do not assume the install worked just because the command exited quietly. List the resolved packages:
flutter pub deps --style=compactLook for the three package names in the output, with json_annotation listed as a direct dependency and the other two as dev dependencies. In the same output you will see the transitive packages that json_serializable brought in, such as source_gen and analyzer. These are the reason it belongs in dev_dependencies.
You can also confirm that the build tool starts:
dart run build_runner buildWith no annotated classes yet, it finishes successfully and reports that it wrote no outputs. A successful empty run proves that the toolchain resolves and launches. The first run is slower than later ones because it compiles the build script and populates a cache in .dart_tool/.
Use dart run build_runner. Older tutorials use flutter pub run build_runner, which is the deprecated form of the same command.
Common errors at this step
Version solving failed
A message that starts with Because ... depends on analyzer ... version solving failed means two packages require incompatible versions of a shared dependency. This usually appears when your project already uses another code generator, such as freezed or riverpod_generator. All generators built on build_runner share analyzer and source_gen, so they must agree on versions.
Try these steps in order:
- Run
flutter pub upgradeto let pub choose newer compatible versions. - Run
flutter pub outdatedto see which package holds the others back. - Upgrade the package that is furthest behind, then retry.
Avoid pinning old versions of json_serializable as a first response. An old generator tends to conflict with a newer SDK later.
Packages in the wrong section
Two mistakes occur often, and they fail differently:
json_annotationindev_dependencies. Imports inlib/may still resolve locally, but the analyzer reports thedepend_on_referenced_packageslint. The setup is wrong for anything other than local experiments.json_serializableindependencies. Everything works, but your app's dependency set carries the generator and the analyzer for no benefit. It is a quality problem, not a runtime error.
"Could not find package build_runner"
This message appears when the dart run command cannot find build_runner in the current package. Check that you are in the project root, the directory that holds the pubspec.yaml you edited. In a monorepo, run the command inside the specific package that has the dependencies.
The generator seems to do nothing
If the build succeeds but no .g.dart file appears, the toolchain is usually fine. The cause is typically a missing annotation or a missing part directive in the model file. The next two chapters cover both.
Optional build configuration
json_serializable works with no configuration file. When you want the same options on every model, you can set them once in a build.yaml file in the project root:
targets:
$default:
builders:
json_serializable:
options:
explicit_to_json: true
field_rename: snakeOptions set here become the defaults for every class. An option written in an individual @JsonSerializable(...) annotation overrides the project-wide value for that class. The class-level options chapter covers what each setting does. For now, remember that this file exists, because it is the usual way to avoid repeating options on dozens of models.
Should generated files be committed?
After the next chapter you will have .g.dart files in your source tree. Teams make different choices about whether to commit them, so decide this early.
| Choice | Benefit | Cost |
|---|---|---|
| Commit `.g.dart` files | The project compiles right after `git clone`. CI needs no generation step. | Generated diffs appear in pull requests. Merge conflicts in generated files are possible. |
| Ignore `.g.dart` files | Cleaner history. No stale output. | Every checkout and CI job must run `build_runner` before it can compile. |
For a small app or a team new to code generation, committing the files is the simpler default. If you ignore them, add *.g.dart to .gitignore and put dart run build_runner build --delete-conflicting-outputs in your CI scripts and onboarding notes. Whichever you pick, apply it to the whole repository.
Keeping the toolchain healthy
- Commit
pubspec.lockfor apps. It keeps the generator version the same across machines, so every developer gets identical generated output. - After upgrading
json_serializable, regenerate all files. Output from different generator versions can differ in small ways, and mixing them produces noisy diffs. - If the build starts failing strangely after a dependency change, run
dart run build_runner cleanand build again. This deletes the build cache in.dart_tool/without touching your source files.
Exercise
You run flutter pub add json_serializable and flutter pub add build_runner, without the dev: prefix. The app compiles and runs. What is wrong with this setup, and what command would you have used instead for these two packages?
Show answer
Both packages are now listed under dependencies, so the app's dependency set includes the generator and its large transitive tree (analyzer, source_gen) even though nothing uses them at runtime. The correct command is flutter pub add dev:build_runner dev:json_serializable, which places them under dev_dependencies. json_annotation stays a regular dependency because the app and the generated code import it at runtime.
Exercise
flutter pub get fails with a version solving error that names analyzer, and your project also uses freezed. Why does this happen, and what is your first step?
Show answer
Both json_serializable and freezed are built on build_runner and share analyzer and source_gen. Their version ranges for those packages do not overlap with what your current constraints allow. The first step is flutter pub upgrade to let pub pick newer compatible versions, followed by flutter pub outdated to find the package holding the others back.
Exercise
Your team ignores .g.dart files in Git. A new developer clones the repository, runs the app, and sees errors saying _$UserFromJson is not defined. What is missing?
Show answer
The generated files are not in the repository, so the developer must create them by running dart run build_runner build --delete-conflicting-outputs after flutter pub get. The fix is to document this step, or add it to a setup script and to CI.