Sub topic 5
Generating Code with `build_runner`
This chapter assumes you know Dart classes, constructors, null safety, pubspec.yaml, and basic JSON maps. You should also have a Flutter project and a model annotated with @JsonSerializable.
json_serializable does not generate code when you save a Dart file. The build_runner package runs a code-generation build. It finds annotations such as @JsonSerializable(), then writes serialization methods into a generated Dart file.
What the build produces
A model usually has a part directive and delegates its methods to generated functions:
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
const User({required this.id, required this.name});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
final int id;
final String name;
Map<String, dynamic> toJson() => _$UserToJson(this);
}The part 'user.g.dart'; directive tells Dart that user.dart and user.g.dart belong to the same library. The generated file can access the private library-level functions that json_serializable creates, such as _$UserFromJson and _$UserToJson.
You normally do not write or edit user.g.dart. It is a build artifact. Change the annotated model instead, then run the generator again.
Running a build
After adding json_annotation as a regular dependency and json_serializable plus build_runner as development dependencies, run:
dart run build_runner build --delete-conflicting-outputsThe command performs one build and exits. The option handles an existing output that conflicts with the file the builder wants to create. Review the command output if generation fails.
| Command | Purpose | Typical use |
|---|---|---|
| `dart run build_runner build --delete-conflicting-outputs` | Generate files once | CI or a manual build |
| `dart run build_runner watch` | Regenerate after changes | Local development |
The watch command stays active and rebuilds when you save a source file:
dart run build_runner watchStop it with Ctrl+C. Run the command from the directory containing pubspec.yaml.
Reading build errors
A missing generated file often means one of these problems:
- The
partfilename does not match the source file.user.dartmust usepart 'user.g.dart';. - The generated build has not run yet.
- An annotation or package import is missing.
- A field type cannot be converted with the current configuration.
- A constructor does not provide the values required by the generated
fromJsoncode.
When a build fails, fix the first useful error in the output before investigating later messages. Generated errors often point to the model declaration that caused them.
Generated files and source control
Teams use different policies for generated files. Committing them makes checkout and some CI workflows simpler, but it can create noisy changes when generated output changes. Ignoring them keeps the repository smaller, but every build environment must run code generation.
Choose one policy and apply it consistently. In either case, CI should run the generator so stale output cannot hide model changes.
Exercise
A User model has part 'user.g.dart';, but dart run build_runner build reports that _$UserFromJson is undefined. What should you check first?
Show answer
Check that the file name is really user.dart, that the annotation and package imports are present, and that the build completed without an earlier error.