Sub topic 3
Turning models into maps and JSON
Storage layers do not accept your Dart classes. shared_preferences takes primitives, files take strings or bytes, and sqflite takes maps of column names to values. This chapter covers the conversion step that sits in front of all three: turning a model into a map or JSON, and turning it back safely.
It assumes you know Dart classes, null safety, and async/await. You should also have seen the Note class in the examples for this tutorial. No packages beyond dart:convert are needed here.
The two formats and where they sit
Two representations do most of the work:
- A map is a
Map<String, Object?>of field names to simple values (int,double,String,bool,null, and lists or maps of those).sqflitereads and writes this form directly. - JSON is a string that encodes the same structure as text. You need it when the target accepts only text or bytes, such as a file or a single preferences value.
The map is the shared middle step. A model converts to a map. A map converts to a JSON string with jsonEncode. Going back is the reverse.
The toMap and fromMap pattern
The Note model from this tutorial uses a pair of methods:
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?,
);
}Three details matter:
toMapwrites theideven when it isnull. A new note has no id yet because the database assigns it. When you insert, you remove the key first (note.toMap()..remove('id')) so SQLite can generate the value.fromMapcasts each value withas. A cast to a nullable type (as String?) accepts a missing key and an explicitnull, because reading a missing key from a map returnsnull.titleis cast to a non-nullableString. If the stored data lacks a title, the cast throws aTypeErrorat load time. That is usually what you want: bad data fails where it is read, not three screens later.
Going from map to JSON and back
jsonEncode accepts a map or list and returns a String. jsonDecode returns dynamic, so you cast the result to the shape you expect.
import 'dart:convert';
void main() {
const note = Note(id: 1, title: 'Groceries', body: 'Milk, eggs');
final text = jsonEncode(note.toMap());
print(text); // {"id":1,"title":"Groceries","body":"Milk, eggs"}
final decoded = jsonDecode(text) as Map<String, Object?>;
final copy = Note.fromMap(decoded);
print(copy.title); // Groceries
final listText = jsonEncode([note.toMap(), note.toMap()]);
final list = (jsonDecode(listText) as List<dynamic>)
.map((e) => Note.fromMap(e as Map<String, Object?>))
.toList();
print(list.length); // 2
}This example needs the Note class above in the same file.
The decoded value is typed Map<String, dynamic> at runtime. Casting it to Map<String, Object?> succeeds because dynamic and Object? are treated the same when checking generic arguments. Casting to Map<String, String> would fail, since the values are not all strings.
Types that JSON and SQLite do not have
Real models contain DateTime, bool, and enums. None of these are valid values for jsonEncode or for sqflite columns. SQLite has no boolean or date type, and JSON has no date type. You pick an encoding and apply it in both directions.
| Dart type | Stored as | Write | Read |
|---|---|---|---|
| `bool` | `int` 0 or 1 | `done ? 1 : 0` | `value == 1` |
| `DateTime` | ISO 8601 `String` in UTC | `toUtc().toIso8601String()` | `DateTime.parse(value)` |
| `enum` | the enum name as `String` | `priority.name` | `Priority.values.byName(value)` |
| nested object | `Map`, or a JSON `String` column | `child.toMap()` | `Child.fromMap(value)` |
Here is a model that uses all three:
import 'dart:convert';
enum Priority { low, normal, high }
class Task {
const Task({
this.id,
required this.title,
this.done = false,
required this.dueAt,
this.priority = Priority.normal,
});
final int? id;
final String title;
final bool done;
final DateTime dueAt;
final Priority priority;
Map<String, Object?> toMap() => {
'id': id,
'title': title,
'done': done ? 1 : 0,
'due_at': dueAt.toUtc().toIso8601String(),
'priority': priority.name,
};
factory Task.fromMap(Map<String, Object?> map) => Task(
id: map['id'] as int?,
title: map['title'] as String,
done: (map['done'] as int? ?? 0) == 1,
dueAt: DateTime.parse(map['due_at'] as String),
priority: Priority.values.byName(
map['priority'] as String? ?? 'normal',
),
);
}
void main() {
final task = Task(
title: 'Pay rent',
done: true,
dueAt: DateTime.utc(2026, 12, 1, 9),
priority: Priority.high,
);
final text = jsonEncode(task.toMap());
print(text);
// {"id":null,"title":"Pay rent","done":1,"due_at":"2026-12-01T09:00:00.000Z","priority":"high"}
final back = Task.fromMap(jsonDecode(text) as Map<String, Object?>);
print(back.dueAt == task.dueAt); // true
print(back.priority); // Priority.high
}The same map works for the file example and for the database. A done value of 1 is valid JSON, so one toMap serves both targets. The cost is a slightly odd-looking JSON file. If the file format matters to you, write a separate toJson that uses real booleans.
Defaults and missing keys
Stored data outlives the code that wrote it. A file saved by version 1 of your app may lack a field that version 3 expects. fromMap is where you handle this.
- For a field added later, use a default:
map['priority'] as String? ?? 'normal'. - For a field that must exist, cast to a non-nullable type and let the error surface.
- For an enum value your code no longer knows,
byNamethrows anArgumentError. If old data may contain removed values, catch that case and choose a fallback explicitly instead of hiding it with a broadtry.
Numbers need extra care
JSON has one number type. jsonDecode('3') returns an int, and jsonDecode('3.0') returns a double. If a field is a double in your model but was written as 3, the cast as double throws. Convert through num:
double price(Map<String, Object?> map) => (map['price'] as num).toDouble();
int count(Map<String, Object?> map) => (map['count'] as num).toInt();Large integers are a second trap. Dart on the web represents all numbers as JavaScript numbers, so integers above 2^53 lose precision. Store such ids as strings.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `type 'String' is not a subtype of type 'int?'` | The stored type differs from the cast | Check what `toMap` wrote. Decide on one encoding. |
| `type '_Map<String, dynamic>' is not a subtype of type 'Map<String, String>'` | The cast is stricter than the data | Cast to `Map<String, Object?>` and cast each value. |
| `JsonUnsupportedObjectError` | `jsonEncode` met a `DateTime`, enum, or custom object | Convert it in `toMap`, or pass a `toEncodable` callback. |
| `FormatException` from `jsonDecode` | The text is not valid JSON, often an empty or half-written file | Catch it and treat it as missing data. |
| `Null check operator used on a null value` | A required key is absent | Add a default in `fromMap`, or fix the writer. |
jsonEncode accepts a toEncodable callback, but converting inside toMap is easier to test and keeps the format in one place. Another option is to implement toJson() on the model. jsonEncode calls toJson() automatically on objects it cannot encode, so jsonEncode(notes) works for a List<Note> if Note defines toJson. The explicit .map((n) => n.toMap()) used in this tutorial shows the conversion step and avoids that implicit behavior.
When to generate the code
Hand-written conversion is fine for a few models. It becomes repetitive and error-prone once you have dozens, because a renamed field must be updated in three places. Packages such as json_serializable generate toJson and fromJson from annotations, and drift generates typed row classes for databases. The tradeoff is a build step. Start by hand so you understand what the generators produce.
Test the conversion
Conversion code is pure, so test it without a device. The essential test is a round trip: converting to a map and back yields an equal value.
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Note survives a JSON round trip', () {
const note = Note(id: 7, title: 'Plan', body: null);
final text = jsonEncode(note.toMap());
final copy = Note.fromMap(jsonDecode(text) as Map<String, Object?>);
expect(copy.id, 7);
expect(copy.title, 'Plan');
expect(copy.body, isNull);
});
test('missing title fails loudly', () {
expect(
() => Note.fromMap({'id': 1}),
throwsA(isA<TypeError>()),
);
});
}Neither Note nor Task defines ==, so compare fields as shown, or add equality with Equatable or a manual override.
Exercise
A Task is saved to a JSON file by an older app version that had no priority field. The newer Task.fromMap calls Priority.values.byName(map['priority'] as String) with no default. What happens when the file is loaded, and how do you fix it?
Show answer
The map has no priority key, so the read returns null, and null as String throws a TypeError before byName runs. Fix it by reading the value as nullable and supplying a default: Priority.values.byName(map['priority'] as String? ?? 'normal').
Exercise
Why does the chapter store DateTime as toUtc().toIso8601String() instead of writing the DateTime object into the map?
Show answer
jsonEncode and sqflite cannot store a DateTime object, so the map must hold a supported type. An ISO 8601 string is readable, sorts correctly as text, and DateTime.parse restores it. Using UTC avoids the stored moment changing when the user changes time zone.