Learn/Async UI & APIs/Dart Concurrency: Isolates & Isolate.run()

Dart Concurrency: Isolates & Isolate.run()

Run CPU-heavy operations in parallel background Isolates without freezing the Flutter UI thread

12 min~6 min read+50 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. 1. What is an Isolate?
  2. 2. 2. Modern Background Execution: `Isolate.run()`
  3. 3. 3. Long-Running Isolates with SendPort & ReceivePort
  4. 4. This Lesson In Simple Words
  5. 5. Your level focus
  6. 6. One practical habit
  7. 7. Deep Understanding Guide
  8. 8. Why this lesson matters
  9. 9. Study flow for better retention
  10. 10. Quick Glossary

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Dart Concurrency: Isolates & Isolate.run()

One of the most frequent surprises for developers entering Flutter is that async and await do NOT run code on a separate thread.

Dart is single-threaded by default. An asynchronous network call (http.get) or file read does not block the UI because it delegates I/O work to the underlying operating system kernel. However, if you execute a heavy CPU calculation (such as parsing a 20MB JSON array, calculating a hash, or processing an image), that calculation runs directly on the main UI thread, halting animations and causing severe frame drops (jank).

To achieve true multi-core parallel processing in Dart, you must use Isolates.

1. What is an Isolate?

In traditional languages like Java or C++, threads share memory heaps, requiring locks, mutexes, and synchronized blocks to prevent data race conditions.

In Dart, every thread of execution is called an Isolate:

  • Each isolate has its own isolated heap memory.
  • No isolate can directly read or write variables belonging to another isolate.
  • Zero shared memory = Zero race conditions!

Isolates communicate exclusively by passing messages (copies of data or transferred memory buffers) back and forth.

2. Modern Background Execution: Isolate.run()

In Dart 2.19 and Dart 3, Google introduced Isolate.run(). It simplifies 90% of concurrency use cases into a single line.

Isolate.run() automatically:

  1. Spawns a lightweight background isolate.
  2. Executes your closure on that separate CPU core.
  3. Transfers the result safely back to the caller.
  4. Terminates and cleans up the worker isolate immediately.
// Heavy parsing function
List<Product> parseLargeJson(String jsonString) {
  final List<dynamic> decoded = jsonDecode(jsonString);
  return decoded.map((e) => Product.fromJson(e)).toList();
}

// Running off the main UI thread:
Future<List<Product>> loadProductsConcurrently(String jsonString) async {
  // Dispatches parseLargeJson to a background isolate:
  return await Isolate.run(() => parseLargeJson(jsonString));
}

The 16ms Rule of Thumb

💡 The 16ms Rule of Thumb

At 60 FPS, your app has 16.6ms to calculate and paint a frame (at 120 FPS, only 8.3ms). If any synchronous computation takes longer than 10ms, offload it to Isolate.run() immediately.

3. Long-Running Isolates with SendPort & ReceivePort

If you need a continuous background worker (for example, reading high-speed WebSocket audio packets or image filtering), spawning and terminating isolates repeatedly with Isolate.run() has overhead. Instead, set up a persistent isolate with Ports.

dart
1import 'dart:isolate';
2
3// Worker entrypoint running in background isolate
4void backgroundWorker(SendPort mainSendPort) {
5 final workerReceivePort = ReceivePort();
6 // Send worker's port back to main thread
7 mainSendPort.send(workerReceivePort.sendPort);
8
9 // Listen for tasks from main isolate
10 workerReceivePort.listen((message) {
11 if (message is int) {
12 final result = message * message; // Heavy math
13 mainSendPort.send(result);
14 }
15 });
16}
17
18// Spawning from main isolate
19Future<void> startPersistentWorker() async {
20 final mainReceivePort = ReceivePort();
21 await Isolate.spawn(backgroundWorker, mainReceivePort.sendPort);
22
23 // Get the worker's SendPort
24 final workerSendPort = await mainReceivePort.first as SendPort;
25
26 // Send work to background isolate
27 workerSendPort.send(42);
28}

What CANNOT Cross Isolate Boundaries

⚠️ What CANNOT Cross Isolate Boundaries

Isolates cannot pass live UI references (like BuildContext, Widget instances, or open file sockets). Only primitive data, data transfer models, and binary buffers can cross isolate boundaries.

Isolate Optimization Checklist

  • Do not use Isolates for simple network requests; async/await handles I/O efficiently.
  • Use Isolate.run() for short, intense computations (JSON deserialization, filtering large lists).
  • Use persistent Isolate.spawn with ReceivePort for streaming computations (audio, video frames).
  • Never capture BuildContext or Flutter Widget instances inside an Isolate closure.
  • Verify thread offloading in Flutter DevTools Performance view (UI thread remains clear).

This Lesson In Simple Words

Run CPU heavy operations in parallel background Isolates without freezing the Flutter UI thread. Dart is the language behind Flutter, and clear Dart code makes your Flutter UI easier to maintain.

Your level focus

Connect each concept to real app features you can build.

One practical habit

Prefer readable names, explicit intent, and async/await over deeply nested callbacks.

Deep Understanding Guide

Why this lesson matters

When Dart basics are weak, state bugs, null crashes, and async confusion increase quickly.

Study flow for better retention

  1. Map the lesson to one screen, one user action, and one expected output.
  2. Treat each Dart concept as a building block for widgets, services, and tests you will write later.
  3. If you can choose between two approaches and explain why, you are improving.

Common Mistakes To Avoid

  • Ignoring null safety and forcing values with ! without checking data flow.
  • Writing long functions that mix validation, transformation, and side effects together.
  • Using dynamic where a proper type would catch mistakes earlier.
  • Catching broad errors without keeping useful context for debugging.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write a small pure function and test it with edge cases.
  • Convert one callback-based snippet to async/await with proper error handling.
  • Refactor a long function into smaller helper methods with clear names.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Why does an async function with heavy calculations still freeze the Flutter UI?".

Quick Glossary

  • bloc: An event-to-state pattern that separates logic from UI.
  • async: Code that runs over time without blocking the UI thread.
  • animation: Controlled change in UI properties over time.

Lesson Completion Checklist

  • I can explain "Dart Concurrency: Isolates & Isolate.run()" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Ignoring null safety and forcing values with ! without checking data flow.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

Why does an async function with heavy calculations still freeze the Flutter UI?

Dart is single-threaded. async/await does not spawn threads; CPU-intensive calculations block the main event loop unless dispatched to an Isolate.

How does Dart avoid data race conditions and lock contentions between threads?

Dart Isolates do not share memory heaps. Because memory is completely isolated, race conditions and deadlocks are impossible.

Which modern Dart API is the easiest way to run a one-off heavy function on a background core?

Isolate.run() spawns an isolate, runs the closure, returns the result, and terminates the isolate automatically.

Can you pass a BuildContext or Flutter Widget into an Isolate.run() closure?

BuildContext and widgets belong to the main UI isolate and cannot be transferred across isolate memory boundaries.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue