惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
The GitHub Blog
The GitHub Blog
月光博客
月光博客
T
Tailwind CSS Blog
小众软件
小众软件
Y
Y Combinator Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
B
Blog RSS Feed
博客园 - 司徒正美
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 聂微东
Microsoft Security Blog
Microsoft Security Blog
Recent Announcements
Recent Announcements
博客园 - Franky
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Microsoft Azure Blog
Microsoft Azure Blog
T
The Blog of Author Tim Ferriss
GbyAI
GbyAI
Apple Machine Learning Research
Apple Machine Learning Research

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Dart Isolates Deep Dive — compute, SendPort, and Parallel...
kanta13jp1 · 2026-05-01 · via DEV Community

kanta13jp1

Dart Isolates Deep Dive — compute, SendPort, and Parallel Processing Patterns

Dart's main thread runs on a single-threaded event loop. CPU-heavy work blocks that loop, freezing your UI. Isolates are Dart's answer to parallelism — and their "no shared memory" design eliminates entire classes of bugs that plague threaded systems.

Why Isolates?

// This blocks the UI thread for seconds on large datasets
List<int> heavySort(List<int> data) {
  data.sort();
  return data;
}

Enter fullscreen mode Exit fullscreen mode

async/await is concurrency (cooperative scheduling), not parallelism (true simultaneous execution). CPU-bound work requires Isolates.

compute(): Simplest Entry Point

Future<List<int>> sortInBackground(List<int> data) {
  return compute(_sortData, data); // runs in a new Isolate
}

// Must be a top-level or static function
List<int> _sortData(List<int> data) {
  data.sort();
  return data;
}

final sorted = await sortInBackground(bigList); // UI stays responsive

Enter fullscreen mode Exit fullscreen mode

compute() accepts exactly one argument. Wrap multiple values in a Record or Map.

Isolate.run(): Modern compute() (Dart 2.19+)

// Closures work — captures are copied to the new Isolate
Future<String> parseTitle(String jsonStr) async {
  return Isolate.run(() {
    final decoded = jsonDecode(jsonStr) as Map<String, dynamic>;
    return decoded['title'] as String;
  });
}

Future<int> processWithConfig(List<int> data, Config config) async {
  return Isolate.run(() => _process(data, config));
}

Enter fullscreen mode Exit fullscreen mode

Prefer Isolate.run() over compute() for new code. It's more expressive and handles closures.

SendPort / ReceivePort: Bidirectional Channels

// Long-running Isolate with progress reporting
Future<void> startWorker() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(_longRunningTask, receivePort.sendPort);

  receivePort.listen((message) {
    if (message is Map) {
      print('Progress: ${message['progress']}%');
    } else if (message == 'done') {
      receivePort.close();
    }
  });
}

void _longRunningTask(SendPort sendPort) {
  for (int i = 0; i <= 100; i += 10) {
    _doHeavyWork();
    sendPort.send({'progress': i});
  }
  sendPort.send('done');
}

Enter fullscreen mode Exit fullscreen mode

Persistent Worker Isolate Pattern

class IsolateWorker {
  late SendPort _toIsolate;
  final _fromIsolate = ReceivePort();
  final _pending = <int, Completer<dynamic>>{};
  int _nextId = 0;
  late Isolate _isolate;

  Future<void> init() async {
    final ready = Completer<void>();
    _fromIsolate.listen((msg) {
      if (msg is SendPort) {
        _toIsolate = msg;
        ready.complete();
      } else if (msg is ({int id, dynamic result})) {
        _pending[msg.id]?.complete(msg.result);
        _pending.remove(msg.id);
      }
    });
    _isolate = await Isolate.spawn(_worker, _fromIsolate.sendPort);
    await ready.future;
  }

  Future<T> call<T>(dynamic data) {
    final id = _nextId++;
    final c = Completer<T>();
    _pending[id] = c;
    _toIsolate.send((id: id, data: data));
    return c.future;
  }

  void dispose() {
    _isolate.kill();
    _fromIsolate.close();
  }

  static void _worker(SendPort main) {
    final port = ReceivePort();
    main.send(port.sendPort);
    port.listen((msg) {
      if (msg is ({int id, dynamic data})) {
        final result = _process(msg.data);
        main.send((id: msg.id, result: result));
      }
    });
  }

  static dynamic _process(dynamic data) => data; // replace with real work
}

Enter fullscreen mode Exit fullscreen mode

Zero-Copy Transfers: TransferableTypedData

// Default: copy (slow for large buffers)
sendPort.send(largeUint8List);      // O(n) copy cost

// TransferableTypedData: zero-copy transfer
final transferable = TransferableTypedData.fromList([largeUint8List]);
sendPort.send(transferable);         // O(1)

// Receiving side
final received = message as TransferableTypedData;
final data = received.materialize().asUint8List();

Enter fullscreen mode Exit fullscreen mode

Use TransferableTypedData for image/audio buffers above ~1 MB. The performance difference is dramatic.

Real Example: Background Image Processing

import 'package:image/image.dart' as img;

Future<Uint8List> toGrayscale(Uint8List imageBytes) async {
  return Isolate.run(() {
    final image = img.decodeImage(imageBytes)!;
    return Uint8List.fromList(img.encodePng(img.grayscale(image)));
  });
}

// Called from UI — no jank
final grayBytes = await toGrayscale(originalBytes);
setState(() => _displayBytes = grayBytes);

Enter fullscreen mode Exit fullscreen mode

When NOT to Use Isolates

// Spawn cost ~15ms + serialization cost — not worth it for small data
final decoded = json.length > 1024 * 1024     // only above ~1MB
    ? await Isolate.run(() => jsonDecode(json))
    : jsonDecode(json);                          // fast enough on main thread

Enter fullscreen mode Exit fullscreen mode

Over-using Isolates adds latency. Profile before parallelizing.

Flutter 3.7+: Platform Channels from Isolates

// Before 3.7: calling Platform Channels from an Isolate crashed
// After 3.7: pass a RootIsolateToken
void _isolateTask((RootIsolateToken, SendPort) args) {
  BackgroundIsolateBinaryMessenger.ensureInitialized(args.$1);
  // Platform Channels work now
  MethodChannel('com.example/native').invokeMethod('doNativeWork');
}

final token = RootIsolateToken.instance!;
await Isolate.spawn(_isolateTask, (token, sendPort));

Enter fullscreen mode Exit fullscreen mode

Summary

Use Case Recommended API Notes
One-shot heavy work Isolate.run() Simplest, closure support
Flutter one-shot compute() Convenience wrapper
Persistent worker Isolate.spawn + SendPort Bidirectional channel
Large buffer transfer TransferableTypedData Zero-copy

Dart Isolates enforce "share nothing" parallelism. You give up easy shared state and gain freedom from race conditions and deadlocks. For CPU-bound work in Flutter apps, that's an excellent trade.