Sub topic 3
Adding `json_annotation`, `json_serializable`, and `build_runner`
This chapter assumes you know Dart classes, constructors, null safety, Map and List, and the basic structure of a Flutter project. You should also know that a REST API returns JSON text.
Hand-written JSON parsing works for small models, but it becomes repetitive as models grow. The json_serializable package generates that code from annotations on your classes.
Choose the right package
These packages have different jobs:
| Package | Dependency type | Purpose |
|---|---|---|
| `json_annotation` | Regular | Provides annotations such as `@JsonSerializable` |
| `json_serializable` | Development | Generates `fromJson` and `toJson` code |
| `build_runner` | Development | Runs the generator |
Add them from the root directory of your Flutter project:
flutter pub add json_annotation
flutter pub add dev:build_runner dev:json_serializableThe commands update pubspec.yaml and resolve compatible versions. Keep json_annotation as a regular dependency because your application imports it in model files. The generator packages are only needed while developing and building the source code.
Your dependency section will look similar to this:
dependencies:
flutter:
sdk: flutter
json_annotation: ^4.9.0
dev_dependencies:
build_runner: ^2.4.0
json_serializable: ^6.8.0The exact versions may differ. Let Pub choose compatible versions unless your project requires a specific version.
Understand the generation workflow
You write the model and its annotations. build_runner then creates a separate .g.dart file containing the serialization functions.
The generated file is source code, so commit it when your project convention requires generated files in version control. Do not edit it manually. Your next generator run can replace those edits.
Check the package setup with a model
Create lib/models/user.dart:
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
const User({
required this.id,
required this.name,
this.email,
});
factory User.fromJson(Map<String, dynamic> json) =>
_$UserFromJson(json);
final int id;
final String name;
final String? email;
Map<String, dynamic> toJson() => _$UserToJson(this);
}The part directive connects this file to the generated file. The generated functions have names based on the class: _$UserFromJson and _$UserToJson.
At this point, the generated file does not exist. An editor may report errors for those functions until you run the generator.
Run the generator
Run this command once:
dart run build_runner build --delete-conflicting-outputsThe --delete-conflicting-outputs option removes stale generated files that would otherwise prevent the build. Use it when generated output conflicts with a new model definition.
During active development, use watch mode instead:
dart run build_runner watchWatch mode keeps running and regenerates files whenever you save a model. Stop it with Ctrl+C.
> callout note > Generated code is an output of your model source. Change the annotations or class, then run the generator again. Never rely on manual edits inside a .g.dart file.
Exercise
Exercise
Which package should be a regular dependency, and which two packages are development dependencies?
Show answer
jsonannotation is a regular dependency. jsonserializable and build_runner are development dependencies.