Sub topic 13
Offloading Heavy Work with `Isolate.run`
Assume you know Dart functions, Future, async, and await. This chapter explains when asynchronous code is not enough and how Isolate.run moves CPU-heavy work away from the main isolate.
Why `async` Does Not Make CPU Work Faster
Dart code normally runs in an isolate. An isolate has its own memory and event loop. Flutter's main isolate also handles user input, timers, and screen drawing.
async and await help when your code is waiting for something, such as a file, network response, or timer. They do not move a calculation to another thread. A long synchronous loop still blocks the event loop:
int sumTo(int n) {
var total = 0;
for (var i = 1; i <= n; i++) {
total += i;
}
return total;
}If this function runs on Flutter's main isolate with a large value of n, the interface may stop responding until the loop finishes.
A separate isolate is an independent Dart execution context. It has its own event loop and memory. Isolates do not share ordinary mutable objects. They communicate by sending messages, and Dart copies or transfers supported values between them.
Running a Function in Another Isolate
Isolate.run executes a function in a new isolate and returns its result as a Future. The caller can use await while the calculation runs elsewhere.
import 'dart:isolate';
int sumTo(int n) {
var total = 0;
for (var i = 1; i <= n; i++) {
total += i;
}
return total;
}
Future<void> main() async {
print('Starting calculation');
final result = await Isolate.run(() => sumTo(100000000));
print('Result: $result');
}The callback passed to Isolate.run must return a value that Dart can send between isolates. Numbers, strings, lists of sendable values, maps with sendable keys and values, and many simple data objects work well. Avoid relying on shared mutable state because the new isolate cannot directly access the caller's ordinary variables.
This diagram shows the message boundary:
Choosing Isolate.run
Use Isolate.run for CPU-heavy, synchronous work:
- Decoding or transforming a large data set
- Sorting a very large collection
- Parsing complex text
- Performing image or compression calculations
- Running a long mathematical algorithm
Do not use it merely because a function returns a Future. Network and file operations already spend most of their time waiting. An isolate adds startup and message-transfer costs, so a small calculation can be slower when moved.
| Work type | Suitable approach | Reason |
|---|---|---|
| HTTP request | `async` and `await` | The program mostly waits for I/O |
| Small calculation | Normal synchronous function | Isolate setup costs more than the work |
| Large calculation | `Isolate.run` | Keeps the main event loop responsive |
Isolate.run is available on native Dart and Flutter platforms. Dart web applications do not support dart:isolate in the same way, so web code needs a different strategy, such as browser workers or smaller chunks of work.
Errors and Limitations
If the callback throws, the Future returned by Isolate.run completes with an error. Handle it with ordinary asynchronous error handling:
import 'dart:isolate';
int requirePositive(int value) {
if (value <= 0) {
throw ArgumentError('value must be positive');
}
return value * 2;
}
Future<void> main() async {
try {
final result = await Isolate.run(() => requirePositive(-1));
print(result);
} on ArgumentError catch (error) {
print('Calculation failed: $error');
}
}Keep the function self-contained. It should receive its inputs explicitly and return its output explicitly. A closure that captures a database connection, controller, BuildContext, or other non-sendable object may fail when Dart tries to start the isolate.
Isolate.run is designed for one computation and one result. For a long-lived worker that processes many messages, use Isolate.spawn with ports instead.
Exercise
A Flutter function downloads JSON and then spends three seconds sorting a very large list. Which part might belong in Isolate.run, and why?
Show answer
The large-list sorting might belong in Isolate.run because it is CPU-heavy. The download should remain ordinary asynchronous I/O with async and await.