Sub topic 12
Moving heavy work to isolates
This chapter assumes you can write async Dart, run flutter run --profile, and read the Performance view in DevTools. It also assumes you know the earlier idea that the first frame has a time budget, and that work in main() delays it.
Why the UI isolate is a bottleneck
A Dart program runs inside an isolate. An isolate has its own memory heap and a single thread that runs an event loop. A Flutter app starts with one main isolate, often called the UI isolate. It runs your main(), builds widgets, handles gestures and runs layout and painting code.
async and await do not create threads. They only let the event loop do other things while you wait for I/O such as a network response. Once the data arrives, the code after await runs on the same thread. If that code decodes 5 MB of JSON, the UI isolate is busy for that whole time. It cannot build frames, so animations stutter. During startup it cannot reach the first frame.
At 60 Hz a frame has about 16 ms. At 120 Hz it has about 8 ms. Any synchronous task that exceeds that budget drops frames.
Isolates fix this by running Dart code on another thread. They share no memory, so there are no locks and no data races. They communicate only by sending messages.
What belongs in a background isolate
Move work that is CPU-bound and takes a noticeable amount of time. Do not move work that is slow only because it waits.
| Work | Move to an isolate? | Reason |
|---|---|---|
| Decoding a large JSON response | Yes | CPU-bound parsing blocks the UI thread. |
| Sorting or filtering tens of thousands of items | Yes | Pure computation. |
| Parsing a large CSV or XML file | Yes | Pure computation. |
| An `http` request | No | Waiting on the network does not block the thread. |
| Reading a small settings value | No | Spawn cost exceeds the work. |
| Building widgets | No | Widgets must be built on the UI isolate. |
A rough rule is to measure first. If the work takes under a few milliseconds, an isolate adds more cost than it removes. If it takes 10 ms or more on a mid-range device, it is a candidate.
One-off work with Isolate.run
Isolate.run is the simplest API. It starts a new isolate, runs a function in it, returns the result as a Future, and shuts the isolate down.
import 'dart:isolate';
List<int> parseNumbers(String raw) {
return raw.split(',').map(int.parse).toList();
}
Future<List<int>> loadNumbers(String raw) {
return Isolate.run(() => parseNumbers(raw));
}
Future<void> main() async {
final numbers = await loadNumbers('3,1,4,1,5,9');
print(numbers);
}The closure passed to Isolate.run is copied into the new isolate along with every variable it captures. Here that is only the string raw. The returned list is passed back. Isolate.run hands the result back using Isolate.exit. For simple data this transfers ownership of the result without copying it again.
Custom classes can be sent as well, as long as they contain only sendable data. This example decodes JSON into model objects off the UI thread.
import 'dart:convert';
import 'dart:isolate';
class Product {
const Product(this.id, this.name);
final int id;
final String name;
}
Future<List<Product>> parseProducts(String body) {
return Isolate.run(() {
final items = (jsonDecode(body) as List<dynamic>).cast<Map<String, dynamic>>();
return [
for (final item in items) Product(item['id'] as int, item['name'] as String),
];
});
}
Future<void> main() async {
const body = '[{"id": 1, "name": "Pen"}, {"id": 2, "name": "Book"}]';
final products = await parseProducts(body);
print(products.map((p) => p.name).join(', '));
}Flutter also offers compute in package:flutter/foundation.dart. It wraps the same idea but takes a top-level or static function and one argument. It also works on Flutter web, where it runs the function on the main thread. Isolate.run is the more general choice for native targets.
What can and cannot cross the boundary
Messages are copied between heaps. Some rules follow from that.
- Numbers, strings, booleans,
null, lists, maps, sets and simple objects built from them can be sent. - Instances of your own classes can be sent if their fields are sendable. The receiver gets a copy, not the same object.
- Objects that wrap native resources cannot be sent. Examples are sockets, open files held through
dart:iohandles, andReceivePortin some positions. - Closures can be sent only if everything they capture is sendable.
A copy has a cost that grows with the size of the data. If you pass 20 MB in and get 20 MB back, copying can eat part of the benefit. Prefer to pass the smallest input, such as a file path instead of file contents, and return only the result you need.
The fix looks like this.
import 'dart:isolate';
String summarize(List<int> values) => 'count=${values.length}';
class Report {
Report(this.values);
final List<int> values;
Future<String> build() {
final local = values; // copy the field into a local variable
return Isolate.run(() => summarize(local));
}
}
Future<void> main() async {
print(await Report([1, 2, 3]).build());
}Platform channels and plugins in a background isolate
Background isolates do not have the Flutter binding. Before Flutter 3.7, calling a plugin from one failed. Now you can use plugins that rely only on platform channels, if you register the isolate with the root isolate's token.
import 'dart:isolate';
import 'package:flutter/services.dart';
Future<void> doPluginWorkInBackground() async {
final token = RootIsolateToken.instance!;
await Isolate.run(() async {
BackgroundIsolateBinaryMessenger.ensureInitialized(token);
// Call a plugin that supports background isolates here.
});
}Read the token on the UI isolate, because RootIsolateToken.instance is null elsewhere. Check each plugin's documentation, since support is not universal. Anything that touches the widget tree, such as BuildContext, setState or rendering, must stay on the UI isolate.
Long-lived workers
Isolate.run pays the spawn cost on every call. For a task you repeat often, such as filtering as the user types, start one isolate and keep it. This uses Isolate.spawn with a ReceivePort and a SendPort, and it is more code. The pattern is as follows.
- The UI isolate creates a
ReceivePortand spawns the worker, passing it theSendPort. - The worker creates its own
ReceivePortand sends itsSendPortback. - The UI isolate sends requests to that port. The worker sends results back to the first port.
Use this only if measurements show repeated spawning is a problem. Spawning an isolate usually takes on the order of milliseconds, which is small next to the work that justified moving it. A long-lived worker also adds lifecycle code you must test, including shutdown and error handling.
Isolates and app startup
The earlier chapters set up two rules: keep main() lean, and push non-essential work after the first frame. Isolates add a third option for work that is both needed and CPU-heavy.
- Work needed by the first screen: do it in an isolate and show a lightweight placeholder, not a blank screen, until it completes.
- Work not needed by the first screen: schedule it after the first frame, as in
addPostFrameCallback. If it is CPU-heavy, start it in an isolate from there. - Work that depends on plugins: use the background isolate setup above, or leave it on the UI isolate after the first frame.
Errors and cancellation
If the function inside Isolate.run throws, the Future completes with that error. You can catch it with try/catch around the await. A plain Isolate.run has no cancellation. If the user leaves the screen, ignore the result, for example by checking mounted before calling setState. The isolate still runs to completion.
import 'dart:isolate';
int risky(int x) {
if (x < 0) throw ArgumentError('x must not be negative');
return x * 2;
}
Future<void> main() async {
try {
await Isolate.run(() => risky(-1));
} on ArgumentError catch (e) {
print('Caught: ${e.message}');
}
}Verify the gain
- Run the app with
flutter run --profileon a real, mid-range device. Debug mode inflates timings and misleads you. - Open the Performance view in DevTools and trigger the action. Look for frames over the budget in the frame chart before the change.
- Apply the isolate change and repeat. The slow frames should disappear. For startup, compare the time to first frame in
build/start_up_info.jsonfrom--trace-startup. - In the CPU profiler, confirm the heavy function now shows on a separate thread and not on the UI thread.
Common errors to check for:
- The closure captures
thisand fails with an unsendable object error. - The data copy is so large that total latency gets worse.
- The code calls a plugin without
BackgroundIsolateBinaryMessenger.ensureInitialized. - The result is applied after the widget was disposed.
- The change is verified in debug mode only.
Exercise
A screen decodes a 4 MB JSON string in initState using jsonDecode, and the first frame after navigation drops several frames. A developer wraps the call as Isolate.run(() => _decode(raw)), where _decode is an instance method of the State class, and gets an error at runtime. What is the likely cause, and how do you fix it?
Show answer
The closure captures this, which references the State object and things that cannot be sent to another isolate. Make _decode a top-level or static function, copy any needed fields into local variables, and call Isolate.run(() => decode(raw)). Then check mounted before calling setState with the result, and confirm the improvement in profile mode in DevTools.
Exercise
Your team wants to move an http.get call into an isolate to "speed it up". Is this a good change? What should be moved instead?
Show answer
No. The request spends its time waiting on the network, and await already lets the UI isolate keep running during that wait. An isolate adds spawn and copy cost with no benefit. If decoding the large response body is slow, move that CPU-bound decoding step into Isolate.run.