A reusable worker needs a message protocol, not access to another isolate’s private variables. Begin with one request and one response. Include error and shutdown decisions before extending the worker into a long-lived service.
Worked example
Language requirement: Dart 3.0 or later. Use a local Dart project; read the file/dependency instructions before running this example.
import 'dart:isolate';
void sumWorker((SendPort, List<int>) input) {
final (reply, values) = input;
reply.send(values.fold<int>(0, (sum, value) => sum + value));
}
Future<void> main() async {
final replies = ReceivePort();
final worker = await Isolate.spawn(
sumWorker, (replies.sendPort, [10, 20, 30]), onError: replies.sendPort,
);
try {
final reply = await replies.first.timeout(const Duration(seconds: 3));
if (reply is! int) throw StateError('Worker failed to return a total.');
print('Total: $reply');
} finally {
replies.close();
worker.kill(priority: Isolate.immediate);
}
}
Follow the data and control flow
The record carries a reply port and the data to aggregate. The response is an integer, so the consumer checks that shape before using it. A deadline prevents this learning caller from waiting forever when no result arrives; the finally block owns port and worker cleanup.
For multiple jobs, add request IDs and explicit result/error message types. Decide whether jobs are queued, concurrent or cancelled on shutdown. Keep isolate errors separate from a valid business result and document which values may cross the boundary.
A mistake to avoid
A ReceivePort can keep the process alive when forgotten. Sending a closure that captures an unsendable object can fail before useful work starts. Also avoid killing a shared worker that other consumers own; this example owns the worker exclusively.
Practice and verification
Add a deliberate worker error and confirm the caller terminates with a meaningful failure. Design a request-ID envelope for two queued jobs. Explain how a long-lived worker should stop accepting work and drain its current job before shutdown.