D
OOP & SOLIDHard40 XP5 min read

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

AspectThreadsIsolates
MemoryShared heap (race conditions)Separate heaps (no sharing)
CommunicationShared variables / locksMessage passing via SendPort
SafetyManual synchronizationNo race conditions by design
CostLighterHeavier (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

dartcompute() vs Isolate.spawn for background JSON parsing
Output
// 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.

#isolates#concurrency#compute#message-passing