Dart Async Guide: Future, Stream, and Isolate — When to Use Each
Source: Dev.to
Why Async Matters
// ❌ BAD: synchronous call blocks the UI
void fetchData() {
final data = http.get('https://api.example.com/data'); // 2s wait
// UI freezes for 2 seconds
}
// ✅ GOOD: async keeps the UI responsive
Future fetchData() async {
final data = await http.get('https://api.example.com/data');
// UI continues responding while waiting
}
Future: One-Time Async Value
Future fetchUsername(String userId) async {
final response = await supabase
.from('profiles')
.select('username')
.eq('id', userId)
.single();
return response['username'] as String;
}
final username = await fetchUsername('user-123');
Error handling
try {
final username = await fetchUsername('user-123');
} on PostgrestException catch (e) {
debugPrint('DB error: ${e.message}');
} catch (e) {
debugPrint('Error: $e');
}
Parallel execution with Future.wait
// Sequential: 2 seconds total
final profile = await fetchProfile(userId); // 1s
final settings = await fetchSettings(userId); // 1s
// Parallel: 1 second total
final results = await Future.wait([
fetchProfile(userId),
fetchSettings(userId),
]);
final profile = results[0] as Profile;
final settings = results[1] as Settings;
Stream: Continuous Async Values
// Supabase Realtime: receive messages as they arrive
Stream> watchMessages(String roomId) {
return supabase
.from('messages')
.stream(primaryKey: ['id'])
.eq('room_id', roomId)
.order('created_at');
}
// Use in a widget
StreamBuilder>(
stream: watchMessages('room-1'),
builder: (context, snapshot) {
if (!snapshot.hasData) return const CircularProgressIndicator();
final messages = snapshot.data!;
return ListView.builder(
itemCount: messages.length,
itemBuilder: (_, i) => MessageTile(message: messages[i]),
);
},
);
Building your own Stream
Stream countDown(int from) async* {
for (int i = from; i >= 0; i--) {
yield i;
await Future.delayed(const Duration(seconds: 1));
}
}
await for (final count in countDown(10)) {
print(count); // 10, 9, 8, ... 0
}
Isolate: CPU‑Heavy Work on a Separate Thread
// ❌ BAD: heavy work on main thread → jank
String parseHugeJson(String json) {
return processJson(json); // 3 seconds — UI freezes
}
// ✅ GOOD: offload to an Isolate (Flutter 3.7+)
Future parseHugeJsonInBackground(String json) async {
return Isolate.run(() => processJson(json));
}
For Flutter
Future parseHugeJson(String json) async {
return compute(processJson, json);
}
String processJson(String json) {
// runs in a background isolate
return jsonDecode(json).toString();
}
Decision Guide
One-time async value → Future / async‑await
Continuous stream of values → Stream / StreamBuilder
CPU‑intensive processing → Isolate.run / compute
Multiple concurrent tasks → Future.wait
Combining with Riverpod
@riverpod
Future userProfile(UserProfileRef ref) async {
return fetchProfile(ref.watch(authUserIdProvider));
}
@riverpod
Stream> chatMessages(ChatMessagesRef ref, String roomId) {
return watchMessages(roomId);
}
Summary
Choose based on three questions: how long to wait, how many values, and how CPU‑heavy the work is.
- Start with
awaitfor simple one‑time async operations. - Add a
Streamwhen you need real‑time updates. - Use an
Isolate(orcompute) when the CPU is the bottleneck.