Sub topic 5
Generating code with build_runner
This chapter covers what happens when you run build_runner, what the generated file contains, and how to fix the errors that usually appear. It assumes you finished the previous chapter, so json_annotation, json_serializable, and build_runner are in pubspec.yaml, and lib/user.dart has the annotated User class with part 'user.g.dart';. You should also be comfortable running commands in a terminal.
What build_runner does
build_runner is a build tool for Dart. It scans your package for files that match the inputs of registered builders, runs those builders, and writes the results to disk. json_serializable is one such builder. It looks for classes annotated with @JsonSerializable() and writes a Dart source file next to each one.
It is not a runtime library. It runs on your machine during development, and the output is ordinary Dart code that gets compiled into your app. Nothing in the generated code uses reflection, which is why it works with Flutter's tree shaking and ahead-of-time compilation.
The three commands
You will use three commands. Run them from the project root.
dart run build_runner build --delete-conflicting-outputsbuild performs one pass and exits. Use it in scripts, in CI, and after pulling changes from teammates.
dart run build_runner watch --delete-conflicting-outputswatch keeps running and regenerates whenever you save a file. Leave it in a spare terminal tab while you edit models. It only rebuilds the files affected by a change, so it is much faster after the first run.
dart run build_runner cleanclean deletes the build cache in .dart_tool/build. It does not remove your .g.dart files. Use it when the builder seems to ignore your changes, then run build again.
The --delete-conflicting-outputs flag tells the tool to delete any existing generated file it did not create in the current cache. Without it, a first run in a project that already contains a .g.dart file (for example, one you checked out from git) can stop with a "Conflicting outputs" message. With the flag, the stale file is replaced. It only deletes files that the builders are about to write, so it does not touch your own source.
The part directive links the two files
Generation works because of one line in your model file:
part 'user.g.dart';A part file is not a separate library. The compiler treats user.g.dart as if its contents were written inside user.dart. That is why the generated functions can be private. Names that start with _$ are private to the library, and user.dart can call _$UserFromJson even though it lives in another file.
The generated file starts with a matching part of 'user.dart';. The file name in your part line must be the model file's name with .g.dart in place of .dart. If it does not match, the builder writes the output to the correct name and your part line points at nothing.
What the generated file contains
After a successful run, lib/user.g.dart looks roughly like this for the User model:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'user.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
User _$UserFromJson(Map<String, dynamic> json) => User(
id: (json['id'] as num).toInt(),
name: json['name'] as String,
email: json['email'] as String?,
);
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
'id': instance.id,
'name': instance.name,
'email': instance.email,
};The exact formatting changes between package versions, but the structure stays the same. Read it at least once. It shows you what the library does with your declarations:
- Each constructor parameter becomes a named argument. The generator calls your constructor, so the constructor must accept every field you want deserialized.
requiredfields use a plain cast such asas String. A missing or wrongly typed value throws aTypeError.- A nullable field uses
as String?. A missing key and an explicitnullboth givenull. - Integers pass through
numand.toInt(), so a JSON value like1.0still decodes into anintfield. toJsonwrites every field, includingnullones, unless you change that withincludeIfNull(covered in the class options chapter).
Never edit this file. The next build overwrites your changes. If the output is wrong, change the model or its annotations.
Using the generated code
Once user.g.dart exists, User.fromJson and toJson work like any other methods:
import 'dart:convert';
import 'user.dart';
void main() {
const body = '{"id": 7, "name": "Grace", "email": null}';
final user = User.fromJson(jsonDecode(body) as Map<String, dynamic>);
print(user.name); // Grace
print(jsonEncode(user.toJson()));
// {"id":7,"name":"Grace","email":null}
}Should you commit generated files?
There are two common policies:
| Policy | Advantages | Drawbacks |
|---|---|---|
| Commit `.g.dart` files | The project builds right after clone. Reviewers can see generated changes. CI needs no build step. | Merge conflicts in generated files. Diffs get noisy. A forgotten regeneration leaves stale code. |
| Ignore `*.g.dart` | Small diffs and no generated conflicts. | Every developer and every CI job must run `build_runner build` before analyzing, testing, or building. |
Either works. Pick one per repository and enforce it. If you commit them, add a CI step that runs the build and fails when git diff --exit-code shows changes. If you ignore them, add *.g.dart to .gitignore and document the build command in the README.
Configuring the builder with build.yaml
You can set class-level options once for the whole package instead of repeating them in every annotation. Create build.yaml in the project root:
targets:
$default:
builders:
json_serializable:
options:
explicit_to_json: true
field_rename: snakeEvery @JsonSerializable() in the package now behaves as if it had explicitToJson: true and fieldRename: FieldRename.snake. Options written in an annotation still override the file. Option names in build.yaml use snake_case, while annotation parameters use camelCase.
You can also restrict which files the builder scans, which speeds up large projects:
targets:
$default:
builders:
json_serializable:
generate_for:
- lib/models/**Changing build.yaml invalidates the cache, so the next build regenerates everything.
Common errors and fixes
Most failures fall into a few groups.
Analyzer errors before the first build. Before user.g.dart exists, your editor reports _$UserFromJson as undefined and the part directive as pointing at a missing file. These are expected. Run build and they go away.
Nothing is generated. Check these in order:
- The
partline is missing or has the wrong file name. - The class has no
@JsonSerializable()annotation, or the file is outside thegenerate_forpaths. json_serializableis underdependenciesinstead ofdev_dependencies, or is missing. The command from the setup chapter,flutter pub add dev:build_runner dev:json_serializable, puts both in the right place.- The build cache is stale. Run
dart run build_runner clean, then build again.
"Conflicting outputs". A .g.dart file exists that the cache does not know about. Add --delete-conflicting-outputs.
Constructor and field mismatch. The generator fails with a message naming a field when a serializable field cannot be set through the constructor, or when the type is not supported (for example a custom class that has no fromJson). Add the field to the constructor, or annotate the nested type with @JsonSerializable() too. For types the library cannot handle at all, you need a JsonConverter, covered later.
toJson returns raw objects for nested classes. This is not a build failure. The generated code puts the nested object itself in the map, and jsonEncode then calls its toJson for you. If you inspect the map directly, you see instances instead of maps. Set explicitToJson: true to get plain maps.
Slow or looping watch mode. If watch rebuilds constantly, a generated file may be inside a watched path that also triggers the builder. Keep generated output beside the source, and use generate_for to narrow the inputs.
Checking your result
A quick way to confirm that generation worked is to analyze the project and run a test. First analyze:
dart analyzeThen run your tests:
flutter testIf dart analyze reports no undefined _$... names, the part file is linked correctly. The round-trip test in a later chapter confirms that the generated code behaves as you expect.
Exercise
You cloned a repository that ignores *.g.dart. The editor shows "Undefined name _$OrderFromJson" in order.dart. Which command fixes it, and why is the error expected?
Show answer
Run dart run build_runner build --delete-conflicting-outputs. The _$OrderFromJson function lives in order.g.dart, which is ignored by git and so does not exist in a fresh clone. The analyzer cannot find it until the builder writes the file.
Exercise
You renamed lib/user.dart to lib/account.dart and ran build, but account.g.dart is not linked to the model. What must you change in the model file, and what should the generated file declare?
Show answer
Change the directive to part 'account.g.dart';. The generated file then starts with part of 'account.dart';. The part file name must match the model file name with .g.dart instead of .dart.
Exercise
What is the difference between build and watch, and when would you use clean?
Show answer
build runs one generation pass and exits, which suits scripts and CI. watch keeps running and regenerates changed files on every save, which suits active development. clean deletes the build cache in .dart_tool/build and is used when the builder ignores changes or behaves as if its state is stale. It does not delete .g.dart files.