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

推荐订阅源

J
Java Code Geeks
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
M
MIT News - Artificial intelligence
G
Google Developers Blog
P
Proofpoint News Feed
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客
爱范儿
爱范儿
罗磊的独立博客
腾讯CDC
Hugging Face - Blog
Hugging Face - Blog
博客园 - 叶小钗
Vercel News
Vercel News
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
C
Check Point Blog
美团技术团队
宝玉的分享
宝玉的分享
Microsoft Security Blog
Microsoft Security Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

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 Async Deep Dive — Mastering Future, Stream, and Isol...
kanta13jp1 · 2026-04-29 · via DEV Community

kanta13jp1

Dart Async Deep Dive — Mastering Future, Stream, and Isolates

async/await is the surface. Underneath is a three-layer system: Future, Stream, and Isolate. Here's a complete breakdown of when and how to use each.

Future — Single Async Value

Future<String> fetchUser(String id) async {
  final response = await http.get(Uri.parse('/users/$id'));
  return response.body;
}

// Error handling
Future<User> safeGetUser(String id) async {
  try {
    return await userRepo.get(id);
  } on NotFoundException {
    throw UserNotFoundError(id);
  } catch (e, stack) {
    log.error('Unexpected', error: e, stackTrace: stack);
    rethrow;
  }
}

// ❌ Sequential (3 seconds total)
final user = await getUser();
final prefs = await getPrefs();

// ✅ Parallel (2 seconds max)
final [user, prefs] = await Future.wait([getUser(), getPrefs()]);

// Timeout
final data = await fetchData().timeout(
  const Duration(seconds: 10),
  onTimeout: () => throw TimeoutException('Timed out'),
);

Enter fullscreen mode Exit fullscreen mode

Stream — Multiple Async Values

// Generator
Stream<int> countDown(int from) async* {
  for (int i = from; i >= 0; i--) {
    yield i;
    await Future.delayed(const Duration(seconds: 1));
  }
}

await for (final n in countDown(10)) { print(n); }

// StreamController (manual)
final ctrl = StreamController<String>();
ctrl.add('hello');
ctrl.add('world');
ctrl.close();

ctrl.stream.listen(print, onError: print, onDone: () => print('done'));

Enter fullscreen mode Exit fullscreen mode

StreamBuilder in Flutter

StreamBuilder<List<Message>>(
  stream: supabase
      .from('messages')
      .stream(primaryKey: ['id'])
      .order('created_at'),
  builder: (context, snapshot) {
    if (snapshot.hasError) return ErrorView(error: snapshot.error!);
    if (!snapshot.hasData) return const CircularProgressIndicator();
    return MessageList(messages: snapshot.data!);
  },
)

Enter fullscreen mode Exit fullscreen mode

Stream Transformations

final processed = rawStream
    .where((v) => v > 0)
    .map((v) => v * 2)
    .distinct()
    .debounceTime(const Duration(milliseconds: 300))  // rxdart
    .take(10);

Enter fullscreen mode Exit fullscreen mode

Isolate — True Parallelism

Dart is single-threaded by default. Isolates run on separate threads — use them for CPU-heavy work that would block the UI.

// compute() — high-level, simplest API
final result = await compute(parseJsonInBackground, largeJsonString);

String parseJsonInBackground(String json) {
  // Runs in a separate isolate — UI stays smooth
  return expensiveParse(json);
}

Enter fullscreen mode Exit fullscreen mode

// Isolate.run() — Dart 2.19+
final result = await Isolate.run(() => expensiveCalculation(data));

Enter fullscreen mode Exit fullscreen mode

// Bidirectional communication (advanced)
Future<void> spawnWorker() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(_worker, receivePort.sendPort);

  final sendPort = await receivePort.first as SendPort;
  final reply = ReceivePort();
  sendPort.send([data, reply.sendPort]);
  final result = await reply.first;
}

void _worker(SendPort main) {
  final port = ReceivePort();
  main.send(port.sendPort);
  port.listen((msg) {
    final [data, SendPort replyTo] = msg as List;
    replyTo.send(process(data));
  });
}

Enter fullscreen mode Exit fullscreen mode

Decision Guide

Task Use
API calls, DB queries Future + async/await
Real-time data, WebSocket Stream + StreamBuilder
JSON parse >1MB compute() / Isolate.run()
Image processing, audio Isolate (bidirectional)

Common Pitfalls

  • Sequential awaits when parallel is possibleFuture.wait()
  • Spawning Isolates for small tasks → overhead > gain; profile first
  • Not cancelling streams → memory leaks; always cancel subscriptions in dispose()
  • Missing error handling on Streams → silent failures; always pass onError

What's the trickiest async pattern you've dealt with in Flutter/Dart? Drop a comment — I'm particularly curious about real-world Isolate use cases.