Sub topic 3
Offloading a task with Isolate.run
This chapter covers Isolate.run, the standard way to move one piece of work off the calling isolate. It assumes you know Dart async/await and Future, and that you understand why a long synchronous computation blocks the event loop. It also assumes you know that each isolate has its own heap. If those ideas are unfamiliar, review the previous two chapters first.
What Isolate.run does
Isolate.run has this signature:
static Future<R> run<R>(FutureOr<R> Function() computation, {String? debugName})You pass a closure with no parameters. Dart starts a new isolate, runs the closure there, and completes the returned Future with the closure's result. When the computation finishes, the new isolate shuts down. You never see a ReceivePort, a SendPort, or a handle to the isolate.
Here is a typical use, parsing a large JSON string:
import 'dart:convert';
import 'dart:isolate';
Future<List<Map<String, dynamic>>> parseRecords(String raw) {
return Isolate.run(() {
final decoded = jsonDecode(raw) as List<dynamic>;
return [for (final e in decoded) e as Map<String, dynamic>];
});
}
Future<void> main() async {
final raw = jsonEncode([
for (var i = 0; i < 3; i++) {'id': i, 'name': 'item $i'},
]);
final records = await parseRecords(raw);
print(records.length); // 3
}The calling isolate stays free while jsonDecode runs. In a Flutter app, that means frames keep rendering while a large payload is parsed.
What happens internally
Isolate.run bundles several steps you would otherwise write by hand:
- It creates a
ReceivePortfor the result. - It spawns an isolate with your closure.
- In the new isolate it runs the closure and awaits the result if the closure is asynchronous.
- It sends the result or error back and ends the isolate.
- It completes the
Futurein the caller.
Two details about copying matter for performance.
- Going in: the closure and every variable it captures are copied into the new isolate. A large captured list costs time proportional to its size.
- Coming out:
Isolate.runreturns the result usingIsolate.exit. That call hands the result's memory to the receiving isolate without copying it, in constant time. A large result is cheap to return, though it must still be a sendable object.
Because of the asymmetry, a task that takes a big input and returns a small summary pays for the input copy. A task that builds a big structure from small inputs returns it cheaply.
No shared state, including globals
A new isolate has its own heap and its own copy of every top-level and static variable. Those variables start from their initial values, not from whatever the calling isolate has set.
import 'dart:isolate';
int counter = 0;
Future<void> main() async {
counter = 10;
final inside = await Isolate.run(() {
counter++;
return counter;
});
print('inside: $inside'); // inside: 1
print('main: $counter'); // main: 10
}The closure sees counter at its initial value of 0, not 10. The increment happens on the worker's copy and is discarded when the isolate exits. If your computation depends on configuration kept in a global or a singleton, pass the configuration in explicitly as a captured local. Code that relies on a global being initialized elsewhere, such as a service locator filled in at startup, will find it empty in the worker.
Returning results
The closure's return value becomes the Future's value. It must be a sendable object. Numbers, strings, booleans, null, lists, maps, sets, records, and typed data are all fine, provided their elements are sendable too. The next chapters cover exactly what can be sent and what happens to objects that cannot be.
You can return a record to give back several values without defining a class:
import 'dart:isolate';
Future<(int min, int max)> findRange(List<int> values) {
return Isolate.run(() {
var lo = values.first;
var hi = values.first;
for (final v in values) {
if (v < lo) lo = v;
if (v > hi) hi = v;
}
return (lo, hi);
});
}
Future<void> main() async {
final (lo, hi) = await findRange([4, 9, -2, 7]);
print('$lo..$hi'); // -2..9
}The closure may also be async. Isolate.run awaits the returned future inside the new isolate, so you can use asynchronous APIs there, such as dart:io file reads. The isolate stays alive until that future completes.
Running several jobs in parallel
Each call creates its own isolate, so independent calls run in parallel on separate threads. Combine them with Future.wait:
import 'dart:isolate';
int sumTo(int n) {
var s = 0;
for (var i = 1; i <= n; i++) {
s += i;
}
return s;
}
Future<void> main() async {
final results = await Future.wait([
Isolate.run(() => sumTo(100000000)),
Isolate.run(() => sumTo(200000000)),
]);
print(results); // [5000000050000000, 20000000100000000]
}Real parallelism is limited by the CPU cores available. If you start 50 isolates on a four-core phone, they take turns, and each one also costs memory. For many small jobs, group them into a few batches or use a long-lived worker, which a later chapter builds.
Errors and timing
If the closure throws, the returned Future completes with that error, so an ordinary try/catch around await Isolate.run(...) works. A later chapter covers the details, including what happens to stack traces and to errors that cannot be sent.
Starting an isolate is not free. It takes time and memory, typically a few milliseconds on a modern device and more on slow hardware. A computation that takes under a millisecond will run slower through Isolate.run than inline. Measure before you assume the isolate helps.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Reading a global or singleton inside the closure | The worker sees an uninitialized copy | Capture the needed value in a local |
| Capturing `this` by using an instance member in the closure | The whole object is copied, or sending fails | Copy the needed field to a local first |
| Wrapping tiny work in `Isolate.run` | Spawn cost exceeds the work | Run it inline |
| Returning an object that holds a socket, port, or native handle | Run-time error when sending the result | Return plain data only |
| Expecting to cancel a running job | The work continues to completion | Use a spawned worker with messages |
| Calling plugins from the closure without setup | `MissingPluginException` or similar | Initialize the background messenger (see the plugins chapter) |
Most failures from this table appear at run time, not as compile errors, so test the isolate path with realistic data.
A pattern for choosing the closure's contents
A reliable shape for Isolate.run calls keeps the closure small:
- Gather the inputs into local variables in the caller.
- Call a top-level or static function from the closure, passing those locals.
- Return plain data.
import 'dart:isolate';
int countWords(String text) =>
text.split(RegExp(r'\s+')).where((w) => w.isNotEmpty).length;
Future<int> wordCount(String text) {
return Isolate.run(() => countWords(text));
}
Future<void> main() async {
print(await wordCount('one two three')); // 3
}The worker function is an ordinary top-level function, which you can test directly without any isolate. The Isolate.run wrapper is one line. This also makes the captured values obvious: only text crosses the boundary.
Platform note
Isolate.run works on Dart's native platforms: the VM, Flutter on mobile and desktop, and ahead-of-time compiled executables. Dart compiled to JavaScript for the web does not support isolates in this form, so code that depends on Isolate.run needs another approach there, such as web workers. The platform limits chapter covers this.
Exercise
A function in a Flutter app reads a 5 MB string field from a settings object, then calls Isolate.run(() => process(settings.bigText)), where settings is an instance of a class that also holds a database connection. Inside process, the code also reads a top-level variable appConfig that main filled in at startup. Name two things that can go wrong, and say how to fix each.
Show answer
First, the closure uses settings.bigText, which captures settings itself, so the whole object, including the database connection, must be sent to the new isolate. That can be slow or fail, because a connection holding native resources is not sendable. Fix it by copying the string into a local (final text = settings.bigText;) and capturing only that. Second, the worker isolate has its own copy of appConfig, which still has its initial value rather than the one main set. Fix it by reading appConfig in the caller and passing the needed values to process as arguments or captured locals.
Exercise
You call Isolate.run to build a list of one million integers from a single int input, then return the list. Is the return path expensive because of copying? Why or why not?
Show answer
No. Isolate.run returns its result with Isolate.exit, which transfers ownership of the result's memory to the receiving isolate in constant time, without copying the elements. The input was a single int, so the copy going in is also tiny. The cost is dominated by building the list.