Sub topic 4
Turning JSON into Dart models
This chapter assumes you know Dart classes, null safety, named parameters, Future, async and await, basic Flutter widgets, and how to add a package to pubspec.yaml. You will use those skills to turn an untyped JSON response into objects with a clear Dart type.
Why models matter
JSON is text that represents values such as objects, arrays, strings, numbers, booleans and null. Dart does not know the shape of that data until you describe it.
For example, an API might return:
{
"id": 1,
"title": "Learn Flutter",
"author": {
"name": "Mina"
}
}After jsonDecode, this becomes a Map<String, dynamic>. The dynamic values are convenient, but they remove compile-time checks. A model class gives the response a stable shape and keeps JSON-specific code in one place.
Build a model with `fromJson` and `toJson`
A fromJson factory creates a model from a decoded JSON object. A toJson method converts the model back into a map, which is useful when sending data.
import 'dart:convert';
class Author {
const Author({required this.name});
factory Author.fromJson(Map<String, dynamic> json) {
return Author(name: json['name'] as String);
}
final String name;
Map<String, dynamic> toJson() {
return {'name': name};
}
}
class Article {
const Article({
required this.id,
required this.title,
required this.author,
});
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'] as int,
title: json['title'] as String,
author: Author.fromJson(json['author'] as Map<String, dynamic>),
);
}
final int id;
final String title;
final Author author;
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'author': author.toJson(),
};
}
}
void main() {
const responseBody = '''
{
"id": 1,
"title": "Learn Flutter",
"author": {"name": "Mina"}
}
''';
final decoded = jsonDecode(responseBody) as Map<String, dynamic>;
final article = Article.fromJson(decoded);
print(article.title);
print(article.author.name);
print(jsonEncode(article.toJson()));
}The casts are deliberate. jsonDecode returns dynamic data, so the casts document the expected API contract. If the server sends the wrong type, parsing fails close to the boundary instead of producing confusing errors later in the UI.
Handle nullable and repeated data
An optional JSON field should use a nullable Dart type:
final String? summary = json['summary'] as String?;For an array of objects, cast each item before constructing the model:
final tags = (json['tags'] as List<dynamic>)
.map((item) => item as String)
.toList();For a list of models, use the nested factory:
final comments = (json['comments'] as List<dynamic>)
.map((item) => Comment.fromJson(item as Map<String, dynamic>))
.toList();Do not silently replace missing required fields with empty strings or zeroes. That can hide a server-side contract change. Decide explicitly whether a field is required, nullable, or given a documented default.
The conversion boundary
A useful flow is:
If an endpoint returns an array at the top level, decode it as List<dynamic> and map each item to a model. If it returns an object containing an array, first parse the containing object, then parse its list field.
Exercise
Why should a model use Author.fromJson for the nested author object instead of storing author as dynamic?
Show answer
The nested factory converts untyped JSON into a checked Author value, so the rest of the application can use article.author.name safely and consistently.