What are Isolates in Dart and how do they compare to threads?
TL;DR: Isolates are Dart's concurrency model — independent workers with their own memory heap. They communicate only via message passing (no shared state, no race conditions). Use compute() for simple CPU work, Isolate.spawn for persistent background workers.
Full Answer
Dart is single-threaded per isolate. The main isolate runs your UI. CPU-heavy work (JSON parsing, image processing, encryption) blocks the main thread, causing jank.
Isolate vs Thread
| Aspect | Threads | Isolates |
|---|---|---|
| Memory | Shared heap (race conditions) | Separate heaps (no sharing) |
| Communication | Shared variables / locks | Message passing via SendPort |
| Safety | Manual synchronization | No race conditions by design |
| Cost | Lighter | Heavier (separate heap) |
Flutter's compute() is a convenience wrapper for Isolate.run() — sends data to an isolate, runs a pure function, returns result. Use it for any operation taking >16ms on main thread.
Code Examples
// compute(): auto-spawns isolate, sends data, returns result // Isolate.run(): same but cleaner API (Dart 2.19+) // Isolate.spawn(): for persistent long-lived background workers
Common Mistakes
- ✗Running large JSON decoding on the main isolate — causes frame drops and jank
- ✗Trying to pass non-sendable objects (like Streams, closures over state) to isolates — only primitive values and simple objects can cross isolate boundaries
Interview Tip
Use flutter DevTools 'Performance' view to demonstrate that compute() offloads work to a new isolate. The flame chart shows the main thread free while the background isolate works.