Asynchronous programming with Future, Stream, and async/await
The dart:async library provides support for asynchronous programming with classes such as Future and Stream. These are the fundamental building blocks of asynchronous programming in Dart.
// Fire and forget (not recommended)fetchData(); // No await, result ignored// Wait for completionawait fetchData();// Store future for latervar future = fetchData();// ... do other work ...var result = await future;// Race condition - first to complete winsvar winner = await Future.any([ fetchFromCache(), fetchFromNetwork(),]);// All or nothingtry { var results = await Future.wait([ operation1(), operation2(), operation3(), ]);} catch (e) { // If any fails, all fail}
Single-subscription streams can only be listened to once. Examples: file I/O, HTTP requests.Broadcast streams can be listened to multiple times. Examples: UI events, WebSocket messages.
// Convert to broadcast streamvar broadcast = stream.asBroadcastStream();// Multiple listenersbroadcast.listen((data) => print('Listener 1: $data'));broadcast.listen((data) => print('Listener 2: $data'));// Check stream typeif (stream.isBroadcast) { print('This is a broadcast stream');}
An execution context for asynchronous code. Zones can intercept errors, schedule tasks, and store values.
import 'dart:async';// Run code in a zonerunZoned(() { // This code runs in a custom zone throw Exception('Error in zone');}, onError: (error, stackTrace) { print('Caught error: $error');});// Zone with custom error handlingrunZonedGuarded(() async { // App code here await runApp();}, (error, stackTrace) { // Global error handler logError(error, stackTrace);});// Zone valuesvar zone = Zone.current.fork( zoneValues: {'requestId': '12345'},);zone.run(() { var requestId = Zone.current['requestId']; print('Request ID: $requestId');});
Always handle errors in async code with try-catch or catchError
Don’t mix async/await with then/catchError callbacks
Cancel streams when done to prevent memory leaks
Use await instead of .then() for better readability
Be careful with unawaited futures - they can cause silent failures
Prefer async/await over callbacks for better code readability and error handling. Use Streams for multiple values over time, and Futures for single asynchronous results.