Flutter's UI thread runs at 60Hz or 120Hz, giving developers a strict 16ms (or 8ms) budget per frame. Performing heavy JSON parsing, cryptography, image filtering, or local database migrations directly on the main event loop causes noticeable jank.
Because Dart is single-threaded, true parallel concurrency requires Dart Isolates.
1. How Dart Isolates Work
Unlike threads in C++ or Java that share heap memory, Dart isolates have completely separated heaps and garbage collectors. Communication occurs strictly via message passing (SendPort and ReceivePort).
Main Isolate (UI Thread) Worker Isolate (CPU Heavy)
[ Event Loop ] [ Event Loop ]
| |
SendPort.send(data) ----------> ReceivePort.listen
| | (Compute result)
ReceivePort.listen <---------- SendPort.send(result)2. Using Isolate.run for One-Off Tasks
Dart 2.19+ introduced Isolate.run(), which simplifies background execution without manual port orchestration:
Future<List<GeoPoint>> parseLargeGeoJson(String rawJson) async {
return await Isolate.run(() {
final Map<String, dynamic> decoded = jsonDecode(rawJson);
final features = decoded['features'] as List<dynamic>;
return features.map((f) => GeoPoint.fromMap(f)).toList();
});
}3. Persistent Worker Isolates for Stream Processing
When processing a continuous stream of events (e.g. real-time audio analysis or encrypted Bluetooth packets), spawning an isolate repeatedly introduces overhead. Instead, keep a persistent worker isolate alive:
class CompressionWorker {
late SendPort _toWorker;
final ReceivePort _fromWorker = ReceivePort();
Future<void> init() async {
await Isolate.spawn(_workerEntrypoint, _fromWorker.sendPort);
_toWorker = await _fromWorker.first as SendPort;
}
static void _workerEntrypoint(SendPort toMain) {
final workerPort = ReceivePort();
toMain.send(workerPort.sendPort);
workerPort.listen((message) {
if (message is List<int>) {
final compressed = gzip.encode(message);
toMain.send(compressed);
}
});
}
}By offloading heavy computation, your Flutter UI maintains a flawless, stutter-free 120 FPS frame rate.
