Sub topic 3
Turning Models into Maps and JSON
Assume you know basic Dart classes, null safety, and asynchronous code. This chapter shows how to convert a Dart model into data that storage APIs can save, then rebuild the model when the data is loaded.
A model is a Dart class that represents information in your app. A Map is a collection of key-value pairs. JSON is a text format that represents maps, lists, strings, numbers, booleans, and null values.
Why serialization matters
Storage packages usually do not save arbitrary Dart objects. They work with simpler values:
shared_preferencesstores primitive values such as strings and booleans.- File storage can save text, including JSON.
- SQLite rows are commonly represented as maps.
- Network APIs also commonly use JSON.
Serialization is the process of converting a model into a storable form. Deserialization is the reverse process.
Add `toMap` and `fromMap`
Consider a note with an optional database ID, a required title, and an optional body. The toMap method names each stored field. The fromMap factory reads those fields and creates a new Note.
import 'dart:convert';
class Note {
const Note({this.id, required this.title, this.body});
final int? id;
final String title;
final String? body;
Map<String, Object?> toMap() => {
'id': id,
'title': title,
'body': body,
};
factory Note.fromMap(Map<String, Object?> map) => Note(
id: map['id'] as int?,
title: map['title'] as String,
body: map['body'] as String?,
);
}
void main() {
const original = Note(
id: 1,
title: 'Buy milk',
body: 'Remember oat milk',
);
final map = original.toMap();
final jsonText = jsonEncode(map);
final decoded = Map<String, Object?>.from(
jsonDecode(jsonText) as Map,
);
final restored = Note.fromMap(decoded);
print(jsonText);
print(restored.title);
}The Object? type allows values of different types, including null. The casts in fromMap make the expected types explicit. If stored data has the wrong shape, a cast can fail. Treat that as a data-format error rather than silently accepting invalid data.
Serialize a list of models
A list of models must first become a list of maps. jsonEncode can then convert that list into one JSON string.
final notes = <Note>[
const Note(title: 'First note'),
const Note(title: 'Second note', body: 'Details'),
];
final jsonText = jsonEncode(
notes.map((note) => note.toMap()).toList(),
);
final rawItems = jsonDecode(jsonText) as List<dynamic>;
final restoredNotes = rawItems.map((item) {
final map = Map<String, Object?>.from(item as Map);
return Note.fromMap(map);
}).toList();Keep the field names stable. A file or database may outlive the version of the app that created it. If you rename title to name, older data will not automatically change.
Common errors
- Calling
jsonEncode(note)directly. A custom object is not automatically JSON-encodable. - Forgetting nullable fields. A missing or null value must match the model's type.
- Assuming decoded data has trusted types. Validate or cast every field at the boundary.
- Changing map keys without a migration or compatibility rule.
- Storing dates as
DateTimeobjects. Convert them to a string, such asdate.toIso8601String(), and parse them withDateTime.parse().
Exercise
Why does a model need both toMap and fromMap methods?
Show answer
toMap converts the model into values that storage APIs can save, while fromMap reconstructs the model from those values.