Sub topic 3
When an isolate is worth it
This chapter assumes you know Dart's async and await, Futures, and basic streams. For Flutter examples, you should also know that the UI runs on one thread and must stay responsive.
An isolate is a separate Dart execution unit with its own memory and its own event loop. Isolates do not share objects. They exchange messages instead.
Moving work to an isolate has a cost. Starting one takes time, and copying data between isolates takes time too. Use one when a computation is CPU-heavy and would otherwise block the UI for more than about 16 ms, the length of one frame at 60 frames per second. Work that mostly waits for a network or disk response usually needs async I/O, not an isolate.
Isolate.spawn and ports
Isolate.spawn starts a new isolate that runs a top-level function. A ReceivePort is the receiving end of a message channel. Its sendPort getter gives a SendPort, which you pass to the new isolate so it can reply.
import 'dart:isolate';
void worker(SendPort toMain) {
toMain.send('hello from isolate');
}
Future<void> main() async {
final port = ReceivePort();
await Isolate.spawn(worker, port.sendPort);
print(await port.first);
port.close();
}Building a long-lived worker
For repeated jobs, start one isolate and keep it alive. The worker creates its own ReceivePort, sends that port's SendPort back to the main isolate, and then handles each request message it receives. Send a sentinel value such as null to tell it to close.
Transferring large data
Copying a large byte buffer is slow. TransferableTypedData moves the buffer to the other isolate with less copying. The receiver calls materialize to get the bytes.
import 'dart:isolate';
import 'dart:typed_data';
Future<int> countNonZero(Uint8List bytes) {
final transferable = TransferableTypedData.fromList([bytes]);
return Isolate.run(() {
final data = transferable.materialize().asUint8List();
var count = 0;
for (final b in data) {
if (b != 0) count++;
}
return count;
});
}Calling plugins from a background isolate
A background isolate cannot use platform channels until it is set up. Pass the main isolate's RootIsolateToken and call BackgroundIsolateBinaryMessenger.ensureInitialized. Only plugins that support background isolates will work.
import 'dart:isolate';
import 'package:flutter/services.dart';
Future<void> runWithPlugins() async {
final token = RootIsolateToken.instance!;
await Isolate.run(() {
BackgroundIsolateBinaryMessenger.ensureInitialized(token);
// Plugins that support background isolates can be called here.
});
}Platform limits and the web
Exercise
Exercise
A function takes 300 ms of pure arithmetic and runs on a button tap in a Flutter app. Should you move it to an isolate, and why?
Show answer
Yes. The work is CPU-bound and far longer than one 16 ms frame, so it would freeze the UI. Run it with Isolate.run or compute on a non-web target.