Sub topic 12
Parsing large responses in a background isolate
This chapter assumes you can already fetch a response with the http package and decode it with jsonDecode into model classes. You should also know async/await and the basics of StatefulWidget. Here you will learn when decoding JSON on the UI thread causes dropped frames, how to move that work into a background isolate with compute or Isolate.run, and which mistakes make this fail.
Why decoding can freeze the UI
Dart code runs inside an isolate. An isolate is an independent worker with its own memory and its own event loop. A Flutter app starts in the main isolate, which also builds widgets and paints frames.
await client.get(uri) does not block the main isolate. While the bytes travel over the network, the event loop keeps running and the UI keeps painting. Decoding is different. jsonDecode is plain CPU work in Dart. It runs to completion on whichever isolate calls it, and nothing else on that isolate can run until it finishes.
At 60 frames per second, each frame has about 16 ms. At 120 Hz it has about 8 ms. A payload of a few kilobytes decodes in well under a millisecond. A payload of several megabytes, such as a catalogue of 50,000 items, can take far longer than one frame. While it decodes, animations stall and taps are delayed. This stall is called jank.
Measure before you move work
A background isolate has a cost. Starting a worker takes a few milliseconds, and the input and output are copied between isolates. For small payloads that overhead is larger than the parsing itself. The usual rule is to move parsing off the main isolate only when you can show it takes a noticeable share of a frame.
You can measure this in a plain Dart program. It starts a timer that should tick every 4 ms. It records the longest gap between ticks, which is the longest time the isolate was blocked.
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) =>
Post(id: json['id'] as int, title: json['title'] as String);
final int id;
final String title;
}
List<Post> parsePosts(String body) {
final list = jsonDecode(body) as List<dynamic>;
return list
.map((e) => Post.fromJson(e as Map<String, dynamic>))
.toList();
}
String buildBody(int count) => jsonEncode([
for (var i = 0; i < count; i++)
{'id': i, 'title': 'Post number $i', 'body': 'x' * 200},
]);
Future<Duration> worstGap(Future<void> Function() work) async {
final watch = Stopwatch()..start();
var last = watch.elapsed;
var worst = Duration.zero;
final timer = Timer.periodic(const Duration(milliseconds: 4), (_) {
final now = watch.elapsed;
if (now - last > worst) worst = now - last;
last = now;
});
await work();
await Future<void>.delayed(const Duration(milliseconds: 50));
timer.cancel();
return worst;
}
Future<void> main() async {
final body = buildBody(100000);
final onMain = await worstGap(() async {
parsePosts(body);
});
final inWorker = await worstGap(() async {
await Isolate.run(() => parsePosts(body));
});
print('Longest stall on the main isolate: ${onMain.inMilliseconds} ms');
print('Longest stall with a worker isolate: ${inWorker.inMilliseconds} ms');
}Run it with dart run. The exact numbers depend on your machine, and a debug build is slower than a release build. Always profile in --profile mode on a real device before you decide. Expect the first number to be far larger than 16 ms and the second to stay close to the 4 ms tick.
Moving the parse into a worker
Flutter offers compute in package:flutter/foundation.dart. Dart itself offers Isolate.run in dart:isolate, available since Dart 2.19. Both start a short-lived isolate, run one function in it, return the result, and shut the isolate down.
Use the same Post and parsePosts as above. The fetch function keeps the network call and the status check on the main isolate and moves only the decoding:
import 'dart:isolate';
import 'package:http/http.dart' as http;
Future<List<Post>> fetchPosts(http.Client client) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts');
final response = await client.get(uri);
if (response.statusCode != 200) {
throw Exception('Failed to load posts: ${response.statusCode}');
}
final body = response.body;
return Isolate.run(() => parsePosts(body));
}The compute version is return compute(parsePosts, response.body);. Both do the same job. The two options differ in a few ways:
| Feature | `compute` | `Isolate.run` |
|---|---|---|
| Import | `package:flutter/foundation.dart` | `dart:isolate` |
| Function shape | One top-level or static function with one argument | Any closure, called with no arguments |
| Works in pure Dart | No | Yes |
| Web | Runs the function on the main thread | Not supported |
| Result transfer | Copied back | Handed over without copying where possible |
Isolate.run is the better default for new code. Its closure form lets you pass several values without packing them into a record or a list. compute is still fine, and it is the safer choice if the same code also targets web.
Keep the closure small
A closure passed to Isolate.run carries everything it captures. Two mistakes are common:
- Capturing
this. Inside an instance method, a closure that touches any field captures the whole object. If that object holds ahttp.Client, aBuildContext, a controller, or anything else tied to a native resource, the send fails at runtime. - Capturing the
response. Copyresponse.bodyinto a localStringfirst, as in the code above. The closure then captures only that string.
If the worker needs more than one input, capture several local variables or use a Dart record:
Future<List<Post>> parseWithLimit(String body, int limit) {
return Isolate.run(() => parsePosts(body).take(limit).toList());
}What can cross the boundary
Isolates share no memory. Everything you send in or return is copied, or transferred in a few special cases. These values travel safely:
null, numbers, booleans and strings- Lists, maps and sets whose contents are also sendable
- Instances of your own classes, if all their fields are sendable
Uint8Listand other typed data
These do not:
- Objects tied to native resources, such as sockets, files and
http.Client - Closures or objects that capture such things
- Objects that depend on the UI, such as
BuildContextand widgets
Copying has a price that grows with the size of the data. Returning 100,000 Post objects copies 100,000 objects. Isolate.run ends the worker by exiting it, and that lets Dart pass the result back without a deep copy. compute and other message-based approaches copy.
You can reduce the copying by returning less. If the screen shows 20 rows, have the worker filter, sort or paginate and return only those 20 models.
Errors in the worker
If the function throws, Isolate.run and compute complete the returned future with that error. A FormatException from bad JSON therefore reaches your try/catch on the main isolate, as with any other future. This keeps the error handling from the earlier chapter unchanged. Wrap the call in the same path that turns failures into ApiException.
Future<List<Post>> fetchPostsSafely(http.Client client) async {
try {
return await fetchPosts(client);
} on FormatException catch (e) {
throw ApiException('The server sent invalid JSON: ${e.message}');
}
}Use return await here. A plain return fetchPosts(client) would hand the future back without catching its errors inside the try.
Gotchas and limits
- Web. Browsers do not support Dart isolates.
computestill compiles on web, but it runs the function on the main thread, so you get no benefit there.Isolate.runis not available on web at all. For heavy parsing on web, reduce the payload on the server side with pagination or filtering. - Plugins in the worker. A background isolate has no plugin bindings by default. Pure Dart parsing is fine. Code that calls platform channels inside the worker needs extra setup, so keep plugin calls on the main isolate.
- Per-call start-up cost. Each call creates a new isolate. Do not call
computeonce per list item. Parse the whole payload in one call. - Frequent parsing. If you parse many payloads per second, such as a stream of messages, a long-lived isolate created with
Isolate.spawnand a pair of ports avoids the repeated start-up cost. It takes more code and is rarely needed for REST calls. - UTF-8 decoding.
response.bodydecodes bytes into a string on the main isolate before you send it. For very large bodies you can sendresponse.bodyBytesand calljsonDecode(utf8.decode(bytes))in the worker. Do this only when you know the server uses UTF-8, becausebodyhonors the charset in the response headers and the manual version does not. - Testing. The worker function is an ordinary top-level function, so you can unit test
parsePostsdirectly with a string. A test that usesMockClientstill works withfetchPosts, because the worker only receives the body string.
Deciding whether to use it
- Measure the parse on a mid-range device in profile mode.
- If the stall is well under a frame, keep
jsonDecodeon the main isolate. It is simpler. - If the stall is near or above a frame, move the decode and the
fromJsonmapping intoIsolate.runorcompute. - If the result is still very large, shrink it in the worker before it returns.
Exercise
A teammate writes Future<List<Post>> load() => Isolate.run(() => parsePosts(_response.body)); inside a class that has a _client field of type http.Client and a _response field. The call fails at runtime with an error about an object that cannot be sent. Why does it fail, and how do you fix it?
Show answer
The closure uses the field _response, which means it captures this, the whole object. That object also holds _client, which wraps native network resources that cannot be sent to another isolate. Copy the body into a local variable first, for example final body = _response.body;, and use only that local in the closure: Isolate.run(() => parsePosts(body)). The closure then captures just a String.
Exercise
Why should you keep await client.get(uri) on the main isolate and move only jsonDecode and the model mapping into the worker?
Show answer
Awaiting the network does not block the isolate, because the event loop keeps running while the bytes arrive, so a background isolate gains nothing there. Decoding is CPU work that does block the isolate it runs on, so that is the part worth moving. Moving only the decode also avoids sending an http.Client to the worker, which is not possible.