Sub topic 13
Platform limits and the web
This chapter assumes you can use Isolate.run, know that isolates exchange copied messages, and have seen compute in Flutter. It covers the places where those tools stop working or stop helping. The biggest one is the web, where Dart has no isolates.
Where isolates run
Dart isolates are an feature of the Dart VM and its native runtime. They are not part of the language specification, so each compilation target decides how to handle them.
| Target | `Isolate.run` / `Isolate.spawn` | `compute` (Flutter) | Real parallelism |
|---|---|---|---|
| Android, iOS | Supported | Runs in a separate isolate | Yes |
| macOS, Windows, Linux | Supported | Runs in a separate isolate | Yes |
| Dart VM (CLI, server) | Supported | Not applicable (Flutter API) | Yes |
| Web, compiled to JavaScript | Not supported | Runs on the calling event loop | No |
| Web, compiled to WebAssembly | Not supported | Runs on the calling event loop | No |
The last two rows matter most. Code that parses a large JSON file inside compute moves off the UI thread on a phone. In a browser it still runs on the same thread that paints the page.
Why the web has no isolates
A Dart isolate is a separate heap with its own event loop, scheduled on an operating system thread. JavaScript has no equivalent of that model in a single page. Browser code runs on one main thread, and the only built-in way to get a second thread is a Web Worker. A Web Worker is a separate script with its own global scope, started from the page and reached only through postMessage.
Dart's web compilers (to JavaScript and to WebAssembly) do not translate isolates into Web Workers. Depending on the toolchain and how you import dart:isolate, using Isolate.run or Isolate.spawn on the web either fails to compile or throws UnsupportedError at runtime. Neither outcome moves work off the main thread.
What `compute` does on the web
Flutter's compute was written to hide this difference. On native platforms it runs your function in a separate isolate. On the web it runs the function in the current isolate, after the call returns control to the event loop. The call still returns a Future, so your code keeps working. Nothing runs in parallel.
This has two consequences:
- A long computation still blocks frames and input events for its whole duration.
- Wrapping a function in
computecosts almost nothing on the web, so using it is harmless, but it is not a fix.
import 'package:flutter/foundation.dart';
int fib(int n) => n < 2 ? n : fib(n - 1) + fib(n - 2);
Future<int> computeFib() async {
// Native: separate isolate. Web: same thread, so frames stall.
return compute(fib, 40);
}
bool get runsInParallel => !kIsWeb;kIsWeb is a compile-time constant, so you can use it to pick a different strategy, such as showing a progress indicator or using a smaller workload in the browser.
Writing code that compiles on every target
If you call dart:isolate directly, a web build may refuse to compile your code or may fail when it reaches that call. The usual fix is a conditional import. You define one small interface, then provide one implementation for native targets and one for the web, and Dart picks the right file at compile time.
The first file is the public entry point. It exports the web version by default and swaps in the native version when dart:io is available.
// heavy_runner.dart
export 'heavy_runner_web.dart'
if (dart.library.io) 'heavy_runner_native.dart';The native version uses a real isolate.
// heavy_runner_native.dart
import 'dart:isolate';
Future<R> runHeavy<R>(R Function() task) => Isolate.run(task);The web version has no isolates to use. It yields to the event loop once so the page can paint, then runs the task directly.
// heavy_runner_web.dart
Future<R> runHeavy<R>(R Function() task) async {
await Future<void>.delayed(Duration.zero);
return task();
}Callers import only heavy_runner.dart and call runHeavy(...). The result type is the same everywhere, but the web version still blocks while the task runs.
Real background work on the web
To get parallelism in the browser you need a Web Worker. The approach is:
- Write a separate Dart entry point for the worker that listens for messages and posts results.
- Compile it to JavaScript with
dart compile js, which produces a standalone script file. - Start it from the page through the browser's
WorkerAPI, usingdart:js_interopandpackage:web. - Exchange data with
postMessage.
The data model differs from isolate messages. Web Workers copy data using the browser's structured clone algorithm, which supports primitives, lists, maps, and typed arrays, but not arbitrary Dart objects. You convert your data to JavaScript-friendly shapes on one side and back on the other. Large ArrayBuffer values can be transferred without copying, which plays the role that TransferableTypedData plays on native platforms.
Hand-written workers are tedious, so some packages wrap this pattern to give one worker API that uses isolates on native platforms and Web Workers on the web. Check the maintenance state of any such package before depending on it, since the web interop APIs have changed across recent Dart releases.
Splitting work on the main thread
When you cannot use a worker, you can reduce the damage by cutting the job into chunks and yielding between them. Each yield lets the event loop process input and paint a frame. This does not make the work faster. It only makes the page stay responsive while the work finishes.
Future<int> sumInChunks(int n, {int chunk = 1000000}) async {
var total = 0;
var i = 1;
while (i <= n) {
final end = (i + chunk - 1 < n) ? i + chunk - 1 : n;
for (; i <= end; i++) {
total += i;
}
// Let the event loop handle input and paint a frame.
await Future<void>.delayed(Duration.zero);
}
return total;
}
Future<void> main() async {
print(await sumInChunks(50000000));
}Pick a chunk size that takes a few milliseconds. Too large and frames still drop. Too small and the repeated yielding adds overhead.
Limits that apply on native platforms too
Isolates work on every native target, but they carry limits that also surprise people outside the browser.
- No shared state. Each isolate has its own copy of every
staticfield and top-level variable. A singleton you initialized in the main isolate does not exist in a worker. The worker sees the initial value, or runs the initializer again. Pass in what the worker needs. - Unsendable objects. Objects holding native resources, such as a
ReceivePort, aDynamicLibrary, or objects that implementFinalizable, cannot be sent. Sending one throws anArgumentError. - Plugins. Platform channels work in a background isolate only if you set up
BackgroundIsolateBinaryMessengerand the plugin supports it. Not every plugin does. - Memory. Each isolate has its own heap. A message is copied, so sending a large object graph briefly doubles its memory use. A swarm of workers on a low-end phone can hit memory limits.
- Cores. Isolates give parallelism only up to the number of available cores. Spawning more workers than cores adds scheduling overhead without extra speed.
- Startup cost. Spawning is cheap compared with starting a process, but it is not free. For a task that takes under a millisecond, the isolate costs more than the work.
A practical checklist
Before shipping heavy work, check these points in order:
- Does the app target the web? If yes, plan for a worker or chunking, because isolates will not help.
- Is every value you send sendable, and is the closure free of unneeded captures?
- Does the task need a plugin? If yes, confirm it supports background isolates.
- Does the task depend on static or global state that the worker will not have?
- Have you measured the task on the slowest device you support, on every platform you ship?
Exercise
A teammate wraps a 400 ms image-processing function in compute and confirms that scrolling stays smooth on their Android phone. After release, users on the Flutter web build report that the page freezes for about 400 ms each time. What explains the difference, and what are two ways to improve the web build?
Show answer
On Android, compute runs the function in a separate isolate, so the UI thread keeps rendering. On the web there are no isolates, so compute runs the function on the same event loop as rendering, and the page freezes for the full 400 ms. Two improvements: move the work into a Web Worker (a separately compiled script that communicates with postMessage), or split the processing into small chunks that yield with await Future<void>.delayed(Duration.zero) between them so frames can paint. Reducing the workload, such as processing a smaller image on the web, also helps.
Exercise
In the conditional import example, why does heavy_runner.dart export the web file by default and the native file only under if (dart.library.io)? What would go wrong if the native file contained import 'dart:isolate'; and was imported directly by shared code?
Show answer
dart.library.io is true on native targets and false on the web, so the native implementation is chosen only where dart:io exists and the web file is the fallback everywhere else. If shared code imported the native file directly, the web build would also pull in dart:isolate and Isolate.run, which can fail to compile or throw UnsupportedError in the browser. The conditional export keeps the isolate code out of web builds.
Exercise
Your worker isolate reads Config.apiBase, a static field that the main isolate set at startup. The worker sees the default value instead. Why, and how do you fix it?
Show answer
Each isolate has its own copy of static and top-level state, so the worker never sees the value the main isolate assigned. Pass the value to the worker explicitly, for example as an argument to Isolate.spawn or inside the message, and set it in the worker before use.