Dart
Futures and Streams
Work with single and multiple async values.
By EZ4Code Team
futurestreamasync
Code
// Future: single async value
Future<int> fetchCount() async {
await Future.delayed(Duration(milliseconds: 500));
return 42;
}
// Stream: multiple async values
Stream<int> countDown(int from) async* {
for (var i = from; i >= 0; i--) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
void main() async {
// Future
final count = await fetchCount();
print('Count: $count');
// Stream: await for
await for (final n in countDown(3)) {
print(n); // 3, 2, 1, 0
}
// Stream: listen
final sub = countDown(5).listen(
(n) => print('Tick: $n'),
onDone: () => print('Done'),
onError: (e) => print('Error: $e'),
);
// Cancel subscription
await Future.delayed(Duration(seconds: 2));
await sub.cancel();
// Stream transformations
final doubled = countDown(3).map((n) => n * 2);
await for (final n in doubled) print(n);
}Explanation
Future is a single async value (like Promise); Stream is a sequence of async values (like Observable). async* + yield produces a Stream. await for consumes a Stream sequentially (waits for each event). listen attaches callbacks (non-blocking). Streams support map, where, expand (like Iterables). Use StreamController to create custom streams. Always cancel subscriptions to avoid leaks.
More Dart Snippets
Classes and Constructors
Define classes with named and factory constructors.
Async/Await and Futures
Asynchronous programming with Future and async/await.
Collections (List, Map, Set)
Work with collections and functional operations.
Null Safety
Sound null safety with ? and ! operators.
Generics
Type-safe reusable classes and methods.
Mixins and Extensions
Compose behaviors without inheritance.