Sub topic 14
Parsing large payloads with compute
This chapter assumes you can already write an annotated model with @JsonSerializable, run build_runner, and call a REST endpoint with the http package. It also assumes you know what async and await do in Dart. You will learn why parsing a big response can make a Flutter app drop frames, how to move that work to another isolate with compute or Isolate.run, and where this approach stops helping.
Why parsing can freeze the UI
Dart runs your widget code on the main isolate, and that isolate also builds frames. At 60 frames per second, each frame has about 16 ms. At 120 Hz it has about 8 ms. If a function runs on the main isolate for longer than that, the UI cannot draw and animations stutter.
await http.get(...) does not block the UI. The network wait happens outside Dart code. The work that comes after the response arrives is a different matter. jsonDecode and your generated fromJson calls are ordinary synchronous Dart code. They run to completion on the main isolate. For a 2 KB response this takes microseconds. For a 5 MB response with tens of thousands of objects, it can take hundreds of milliseconds, and the UI freezes for that whole time.
The async keyword does not fix this. An async function still runs on the same isolate. It only lets other work interleave at await points, and a long synchronous jsonDecode call has no await inside it.
Isolates in one paragraph
An isolate is Dart's unit of concurrency. Each isolate has its own memory heap and its own event loop. Isolates share no mutable state. They communicate by sending messages, and the data in a message is copied (with a few exceptions covered below). Because nothing is shared, there are no data races and no locks. The cost is that you must pass everything the worker needs as a message.
Using compute
Flutter's compute function, from package:flutter/foundation.dart, starts a short-lived isolate. It runs a function there with one argument, returns the result as a Future, and shuts the isolate down.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'user.dart';
List<User> parseUsers(String responseBody) {
final decoded = jsonDecode(responseBody) as List<dynamic>;
return decoded
.map((e) => User.fromJson(e as Map<String, dynamic>))
.toList();
}
Future<List<User>> fetchUsers() async {
final response = await http.get(Uri.parse('https://example.com/api/users'));
if (response.statusCode != 200) {
throw http.ClientException('Unexpected status ${response.statusCode}');
}
return compute(parseUsers, response.body);
}Three details matter here.
parseUsersis a top-level function.computeneeds a function that does not capture variables from an enclosing scope.- The argument is the raw
String, not a decodedMap. Decoding is part of the expensive work, so it belongs in the worker. - The return value is a
List<User>. Instances of your own classes can be sent between isolates as long as their fields are simple data such as numbers, strings, lists, maps, and other plain objects.
Using Isolate.run
Since Dart 2.19, dart:isolate has Isolate.run. It takes a closure and runs it in a new isolate. It works in Flutter on mobile and desktop, and it does not need a Flutter import.
import 'dart:convert';
import 'dart:isolate';
import 'package:http/http.dart' as http;
import 'user.dart';
Future<List<User>> fetchUsers() async {
final response = await http.get(Uri.parse('https://example.com/api/users'));
final body = response.body;
return Isolate.run(() {
final decoded = jsonDecode(body) as List<dynamic>;
return decoded
.map((e) => User.fromJson(e as Map<String, dynamic>))
.toList();
});
}Isolate.run accepts a closure, so you do not need a separate top-level function. The closure copies only the variables it captures at the time of the call. Copy what you need into local final variables first, as body is here. If the closure refers to this or to a widget State object, Dart tries to send that whole object to the new isolate. This either fails with an error or sends far more data than you intended.
When the closure finishes, Isolate.run returns its result by exiting the isolate with that value. The result is handed to the main isolate without a deep copy. That makes returning a large list of models cheaper than sending a large message through a port.
| Feature | `compute` | `Isolate.run` |
|---|---|---|
| Import | `package:flutter/foundation.dart` | `dart:isolate` |
| Function shape | A function plus one argument | A closure |
| Works on Flutter web | Yes, but runs on the main thread | No, not supported on web |
| Works in plain Dart | No | Yes |
On Flutter web, compute exists so your code compiles, but it runs the function on the main thread. Web has no Isolate.run support. If you ship to web, the UI still freezes on large payloads. Reduce the payload on the server (pagination, fewer fields) or use a web worker, which is outside this chapter.
What can cross the isolate boundary
Messages between isolates can contain these kinds of values:
null,bool,int,double, andStringList,Map, andSetwhose elements are also sendable- Instances of classes whose fields are sendable, which covers typical
@JsonSerializablemodels Uint8Listand other typed data
Messages cannot contain these:
- Closures sent as message data when they capture unsendable state. A closure passed directly to
Isolate.runis handled specially. - Objects that wrap native resources, such as sockets, file handles, and
ReceivePorts - Objects from Flutter's UI layer, such as
BuildContextandWidget
If you break these rules you get an ArgumentError at the call to compute or Isolate.run, with a message about an unsendable object. The error does not come from inside your parsing code, so read the message for the type name.
Handling errors from the worker
An exception thrown inside the worker is rethrown on the main side when you await the future. You can catch it the same way as any other error.
Future<List<User>> loadUsers() async {
try {
return await fetchUsers();
} on FormatException catch (e) {
// jsonDecode rejected the text.
throw StateError('Server sent invalid JSON: ${e.message}');
} on TypeError catch (e) {
// A cast such as "as List<dynamic>" failed, or a field had the wrong type.
throw StateError('Server JSON had an unexpected shape: $e');
}
}Note the await inside the try. Without it, return fetchUsers() hands back the future and the catch clauses never run. Stack traces from the worker point into the worker's code, so the frames above Isolate.run will not show your widget code.
When not to use a separate isolate
Starting an isolate has a cost. It allocates a new heap and event loop, and the message or result has to be moved across. For small payloads, that overhead is larger than the parsing time. Using compute for a 1 KB response is slower than parsing it inline.
A common rule of thumb is to measure first. Wrap the parse in a Stopwatch and run it in profile mode on a real device, because debug mode is much slower and exaggerates the problem.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'user.dart';
List<User> parseUsers(String responseBody) {
final decoded = jsonDecode(responseBody) as List<dynamic>;
return decoded
.map((e) => User.fromJson(e as Map<String, dynamic>))
.toList();
}
Future<void> measure(String body) async {
final inline = Stopwatch()..start();
parseUsers(body);
inline.stop();
final offloaded = Stopwatch()..start();
await compute(parseUsers, body);
offloaded.stop();
debugPrint('inline: ${inline.elapsedMilliseconds} ms, '
'compute: ${offloaded.elapsedMilliseconds} ms');
}The second number is usually larger, because it includes isolate startup and message passing. The point of compute is not total time. It is that the main isolate stays free during that time. Judge by whether the inline parse takes more than a few milliseconds on your slowest target device. If it does, move it off.
Other ways to reduce the cost
Offloading is not the only option. Consider these when a payload is very large:
- Ask the server for pagination or field selection, so the client receives less data.
- Parse once and cache the model list, so rebuilds do not trigger a second parse.
- For one long-lived stream of updates, use a long-running isolate with
SendPortandReceivePortinstead of starting a new isolate per message. - Decode only what you need. A 20 MB response with 3 fields per item should be modeled with just those 3 fields.
Testing the parsing function
Because parseUsers is a plain function, you can test it without isolates. Isolates add nothing to the correctness of the parsing, so test the function directly and keep one small test for the compute path.
import 'package:flutter_test/flutter_test.dart';
void main() {
test('parseUsers builds a model for each array element', () {
const body = '[{"id":1,"name":"Ada"},{"id":2,"name":"Grace","email":"[email protected]"}]';
final users = parseUsers(body);
expect(users.length, 2);
expect(users.first.name, 'Ada');
expect(users.last.email, '[email protected]');
});
}Exercise
A teammate wraps the whole network call in compute, passing a top-level function that calls http.get and then jsonDecode. The function works on Android but throws on a test that uses a mocked http.Client created in the widget's State. What is the likely cause, and how would you restructure the code?
Show answer
The mocked client is an object from the main isolate, and it is captured or passed into the worker. It holds state (and possibly native resources) that cannot be sent across the isolate boundary, and a worker isolate also does not share the test's mock. Restructure so the network call stays on the main isolate: await client.get(...) there, then pass only response.body (a String) to compute(parseUsers, body). The worker then receives plain data and does only the CPU-heavy decode and fromJson work.