Sub topic 4
Writing an Annotated Model Class
Assume you know Dart classes, named constructors, null safety, Map<String, dynamic>, and the basic structure of a Flutter project. This chapter also assumes that json_annotation, json_serializable, and build_runner are already listed in pubspec.yaml.
An annotated model class describes how one Dart object maps to JSON. The json_serializable package reads the description and generates the repetitive conversion code.
The model class
Suppose an API returns this JSON object:
{
"id": 42,
"name": "Ada Lovelace",
"email": "[email protected]"
}Create a file named 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);
}@JsonSerializable() is an annotation. An annotation is metadata attached to a Dart declaration. It tells the generator to create JSON conversion functions for User.
The part directive connects user.dart with the generated user.g.dart file. The generated file contains private functions named _$UserFromJson and _$UserToJson. You call those functions through the factory constructor and the toJson method instead of writing them yourself.
How the members map
The JSON key and Dart field name match in this example:
| JSON value | Dart member | Dart type |
|---|---|---|
| `id` | `id` | `int` |
| `name` | `name` | `String` |
| `email` | `email` | `String?` |
The required constructor parameters make id and name mandatory when creating a User in Dart. The nullable email field accepts null, and the optional named parameter lets callers omit it.
These are separate concerns:
- Dart constructor requirements control how your application creates an object.
- JSON input controls what
fromJsoncan read. - Generated code checks and casts JSON values according to the declared field types.
A missing required JSON value can cause a runtime error during deserialization. A JSON value with the wrong type, such as "id": "42", also cannot be safely assigned to int.
Generated code as a boundary
The model provides two clear boundaries:
flowchart LR
A[JSON map] -->|fromJson| B[User object]
B -->|toJson| C[JSON map]
D[User annotations and fields] --> E[Generated user.g.dart]
E --> B
E --> CThe fromJson factory is useful when data enters the application from an HTTP response, local storage, or another external source. The toJson method is useful when sending a model to an API or storing it locally.
After generation, usage looks like this:
final user = User.fromJson({
'id': 42,
'name': 'Ada Lovelace',
'email': '[email protected]',
});
final payload = user.toJson();
print(payload['name']); // Ada LovelaceThe map passed to fromJson must already be decoded from a JSON string. json_serializable maps Dart objects and maps; dart:convert handles the string encoding and decoding.
Exercise
What three pieces must be present for this model to use generated serialization: the annotation, the part directive, or the factory methods?
Show answer
All three are needed. @JsonSerializable() requests generation, part 'user.g.dart'; connects the generated library, and fromJson and toJson expose the generated functions through the model's API.