Isolates and Concurrency

27.1 What Are Isolates?

Isolates are independent workers, each with its own memory heap and event loop. They don't share mutable memory, so there are no data races or locks. They communicate by message passing.

Use them for CPU-heavy work (parsing big JSON, image processing, cryptography) to keep the main isolate (UI) responsive.

27.2 Isolate.run (Dart 2.19+): The Simple Way

In Flutter, compute(function, argument) is a convenience wrapper.

import 'dart:convert';
import 'dart:isolate';

Future<List<dynamic>> parseHugeJson(String jsonText) async {
  return Isolate.run(() => jsonDecode(jsonText) as List<dynamic>);   // runs on a new isolate, returns the result
}

int fib(int n) => n < 2 ? n : fib(n - 1) + fib(n - 2);

Future<void> main() async {
  final result = await Isolate.run(() => fib(40));
  print(result);
}

27.3 Long-Lived Isolates with Ports

What can be sent: most objects within the same isolate group (they're copied; immutable objects may be shared), SendPorts, TransferableTypedData (zero-copy transfer of bytes). Closures can be sent within the same isolate group.

Isolate groups share code and have fast spawning.

Web: isolates aren't available. Use web workers (via JS interop), or keep the work async.

import 'dart:isolate';

Future<void> main() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(_worker, receivePort.sendPort);

  final events = receivePort.asBroadcastStream();
  final SendPort workerPort = await events.first as SendPort;

  workerPort.send(10);
  workerPort.send(20);
  await for (final message in events.take(2)) {
    print('Result: $message');
  }
  workerPort.send(null);         // tell the worker to stop
  receivePort.close();
}

void _worker(SendPort mainPort) {
  final port = ReceivePort();
  mainPort.send(port.sendPort);
  port.listen((message) {
    if (message == null) {
      port.close();
      return;
    }
    mainPort.send((message as int) * message);
  });
}

27.4 Concurrency Patterns

Worker pools (spawn N isolates, distribute tasks), pipelines, request/response via ReceivePort + Completer maps. Packages: isolate_manager, squadron, worker_manager.