Sub topic 14
Parsing Large Payloads with `compute`
This chapter assumes you know Dart classes, null safety, Future, jsonDecode, and the generated fromJson methods from json_serializable. It also assumes you have a model such as User with a generated User.fromJson method.
Why JSON parsing can block Flutter
Flutter runs most application code on the main isolate. An isolate is an independent Dart execution context with its own memory. The main isolate also processes frames, input events, and widget updates.
For a small response, decoding JSON and creating model objects is quick. A large response can require noticeable CPU time:
- Convert the JSON string into Dart maps and lists.
- Validate and cast fields.
- Create many model objects with
fromJson. - Build nested lists and objects.
If this work runs on the main isolate, frames may be delayed. The user can see scrolling stutter or a frozen screen.
compute runs a function away from the main isolate on supported native Flutter platforms. It returns a Future, so the UI can remain responsive while parsing finishes.
Make the parser isolate-safe
The callback passed to compute must be a top-level function or a static function. Do not pass a closure that captures a widget, BuildContext, repository, controller, or open connection.
Pass simple data such as a String, a number, or a list of transferable values. For a large JSON response, pass the original string and perform both decoding and model construction in the background isolate.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'user.dart';
List<User> parseUsers(String responseBody) {
final decoded = jsonDecode(responseBody);
if (decoded is! List) {
throw const FormatException('Expected a JSON array of users');
}
return decoded.map((item) {
if (item is! Map) {
throw const FormatException('Each user must be a JSON object');
}
final json = Map<String, dynamic>.from(item);
return User.fromJson(json);
}).toList();
}
Future<List<User>> loadUsers(String responseBody) {
return compute(parseUsers, responseBody);
}The User model and its generated .g.dart file must be available to the isolate. Keep the parser independent from Flutter widgets so it can also be tested directly.
Handle errors from the background isolate
An exception thrown by parseUsers makes the returned Future fail. Handle that failure at the boundary where your application loads data.
Future<void> refreshUsers(String responseBody) async {
try {
final users = await loadUsers(responseBody);
print('Loaded ${users.length} users');
} on FormatException catch (error) {
print('The server returned invalid user data: $error');
} catch (error) {
print('Could not load users: $error');
}
}A parsing isolate does not make invalid data safe. Validate the top-level shape and let User.fromJson report missing or incorrectly typed fields.
Choose the parsing strategy
| Situation | Suitable approach |
|---|---|
| A small JSON response | Parse directly on the main isolate |
| A large response parsed once | Use `compute` |
| Many large responses over time | Consider a dedicated long-lived isolate |
| UI updates needed during parsing | Split the work or process pages incrementally |
On Flutter web, isolate behavior differs because browser execution has different threading rules. Test the target platforms before depending on background CPU execution for performance.
Exercise
Why should parseUsers accept a String instead of receiving a BuildContext or repository?
Show answer
A string is transferable data, while a widget context or repository may contain references that cannot safely cross isolate boundaries. Keeping the callback top-level and data-only allows compute to run it independently.