TExcelTAD
Home › Dart › Dart Isolates

Dart Isolates

Futures and streams handle waiting without blocking, but all your Dart code still runs on one thread. If you start a heavy computation — parsing a 50 MB JSON file, resizing images, crunching numbers — the event loop is stuck until it finishes. In a Flutter app, that means frozen animations ("jank").

The answer is isolates: independent workers that run Dart code truly in parallel on other CPU cores.

What is an isolate?

Threads (Java, C++) Dart isolates
Memory Shared between threads Each isolate has its own heap
Communication Shared variables + locks Messages passed through ports
Data races Possible Impossible by design
Event loop — Each isolate has its own

Your main function runs in the main isolate. Because isolates don't share memory, no locks or mutexes are needed — data is copied (or, for some objects, transferred) between them.

Isolate.run: the easy way

Isolate.run (Dart 2.19+) spawns an isolate, runs one function there, returns its result as a Future, and shuts the isolate down:

dart · try it yourself
import 'dart:isolate';

int countPrimes(int limit) {
  var count = 0;
  for (var n = 2; n <= limit; n++) {
    var isPrime = true;
    for (var d = 2; d * d <= n; d++) {
      if (n % d == 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) count++;
  }
  return count;
}

Future<void> main() async {
  print('main isolate stays free...');
  final primes = await Isolate.run(() => countPrimes(200000));
  print('primes up to 200000: $primes');
}
main isolate stays free...
primes up to 200000: 17984

While the worker counts, the main isolate's event loop keeps processing timers, input and UI frames.

Note: In Flutter, compute(fn, arg) is a thin wrapper around the same idea. On the web, isolates aren't available in the same way; Isolate.run runs code on the main thread there.

Running work in parallel

Start several Isolate.run calls and wait for all of them — each can use a separate core:

dart · try it yourself
import 'dart:isolate';

int sumOfSquares(int from, int to) {
  var total = 0;
  for (var i = from; i < to; i++) {
    total += i * i;
  }
  return total;
}

Future<void> main() async {
  const chunk = 250000;
  final parts = await Future.wait([
    for (var start = 0; start < 1000000; start += chunk)
      Isolate.run(() => sumOfSquares(start, start + chunk)),
  ]);
  print('chunks: ${parts.length}');
  print('total: ${parts.reduce((a, b) => a + b)}');
  print('check: ${sumOfSquares(0, 1000000)}');
}
chunks: 4
total: 333332833333500000
check: 333332833333500000

Long-lived isolates and ports

For an ongoing worker (a background parser, a game AI), spawn an isolate with Isolate.spawn and talk to it through ports. A ReceivePort is a stream of incoming messages; its sendPort can be given to another isolate.

dart · try it yourself
import 'dart:isolate';

// Runs in the worker isolate.
void worker(SendPort toMain) {
  final inbox = ReceivePort();
  toMain.send(inbox.sendPort); // tell main how to reach us

  inbox.listen((message) {
    if (message == 'stop') {
      inbox.close();
      return;
    }
    final text = message as String;
    toMain.send('${text.toUpperCase()} (${text.length} chars)');
  });
}

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

  final messages = fromWorker.asBroadcastStream();
  final toWorker = await messages.first as SendPort;

  for (final word in ['dart', 'isolates', 'rock']) {
    toWorker.send(word);
    print(await messages.first);
  }

  toWorker.send('stop');
  fromWorker.close();
}
DART (4 chars)
ISOLATES (8 chars)
ROCK (4 chars)

What can be sent?

Messages are copied into the receiving isolate. Allowed: null, numbers, strings, booleans, lists, maps, sets, records, SendPorts, TransferableTypedData, and most of your own objects (they're deep-copied). Not allowed: objects holding native resources such as open sockets or ReceivePorts. With Isolate.run, the closure and everything it captures are copied too — so keep captured data small.

When to use isolates

Situation Tool
Waiting for I/O (HTTP, files, DB) async/await — no isolate needed
Short CPU task (< a few ms) Just do it on the main isolate
One heavy computation Isolate.run (or Flutter's compute)
Continuous background processing Isolate.spawn + ports

Tip: Measure first. Spawning an isolate and copying data has a cost, so isolates pay off only when the work is significantly larger than that overhead.

Test yourself

How do Dart isolates share data?

  1. Through shared global variables
  2. By passing messages; each isolate has its own memory
  3. With mutexes
  4. They can't communicate

When is an isolate the right tool?

  1. Waiting for an HTTP response
  2. A CPU-heavy computation that would block the event loop
  3. Reading a small config file
  4. Any async code

What does Isolate.run(fn) return?

  1. The Isolate object
  2. A Future with fn's result
  3. A SendPort
  4. A Stream of results