Stream Transformations
Streams have almost the same toolbox as iterables — map, where, expand, take, skip — plus async-specific operations like asyncMap and distinct. Each operation returns a new stream, so you can build processing pipelines: raw events go in one end, clean, useful values come out the other.
Familiar operations
Stream<int> numbers() async* {
for (var i = 1; i <= 10; i++) {
yield i;
}
}
Future<void> main() async {
final pipeline = numbers()
.where((n) => n.isOdd) // 1 3 5 7 9
.map((n) => n * n) // 1 9 25 49 81
.skip(1) // 9 25 49 81
.take(3); // 9 25 49
await for (final v in pipeline) {
print(v);
}
final words = Stream.fromIterable(['hi there', 'dart rocks']);
print(await words.expand((line) => line.split(' ')).toList());
}9
25
49
[hi, there, dart, rocks]
Async-only operations
| Method | Purpose |
|---|---|
asyncMap(f) |
Like map, but f returns a Future; waits for each in order |
asyncExpand(f) |
Each event becomes a whole stream |
distinct() |
Drops consecutive duplicates |
takeWhile / skipWhile |
Based on a condition |
handleError(f) |
Intercept error events |
timeout(d) |
Error (or fallback) if no event arrives in time |
fold, reduce, toList, first, length |
Turn a stream into a Future |
Future<String> lookupCity(int zip) async {
await Future.delayed(Duration(milliseconds: 5));
return {700000: 'Ho Chi Minh City', 100000: 'Hanoi'}[zip] ?? 'unknown';
}
Future<void> main() async {
final zips = Stream.fromIterable([700000, 700000, 100000, 100000, 100000, 999999]);
final cities = zips.distinct().asyncMap(lookupCity);
await for (final city in cities) {
print(city);
}
final temps = Stream.fromIterable([24, 25, 31, 33, 29, 35]);
final avgOfHot = await temps
.where((t) => t > 30)
.fold<List<int>>([], (acc, t) => acc..add(t))
.then((hot) => hot.reduce((a, b) => a + b) / hot.length);
print('average of hot days: $avgOfHot');
}Ho Chi Minh City
Hanoi
unknown
average of hot days: 33.0
Handling errors in a pipeline
handleError lets a pipeline survive bad events instead of aborting:
Stream<String> rawLines() async* {
yield '10';
yield '20';
yield 'oops';
yield '40';
}
Future<void> main() async {
final parsed = rawLines()
.map(int.parse)
.handleError((Object e) => print('skipped bad line: ${(e as FormatException).source}'));
var sum = 0;
await for (final n in parsed) {
sum += n;
}
print('sum = $sum');
}skipped bad line: oops
sum = 70
Custom transformers
For reusable steps, build a StreamTransformer. StreamTransformer.fromHandlers lets you decide, for each incoming event, what to emit — zero, one or several outputs:
import 'dart:async';
/// Groups incoming items into lists of [size].
StreamTransformer<T, List<T>> batch<T>(int size) {
var buffer = <T>[];
return StreamTransformer.fromHandlers(
handleData: (item, sink) {
buffer.add(item);
if (buffer.length == size) {
sink.add(buffer);
buffer = [];
}
},
handleDone: (sink) {
if (buffer.isNotEmpty) sink.add(buffer);
sink.close();
},
);
}
Future<void> main() async {
final events = Stream.fromIterable(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
await for (final group in events.transform(batch(3))) {
print('sending batch $group');
}
}sending batch [a, b, c]
sending batch [d, e, f]
sending batch [g]
Built-in transformers follow the same idea — for example utf8.decoder and LineSplitter() from dart:convert turn a stream of bytes into a stream of text lines:
final lines = file.openRead().transform(utf8.decoder).transform(const LineSplitter());Writing pipelines as async* functions
Sometimes a hand-written generator is clearer than chained operators, especially when you need state:
Stream<int> runningTotal(Stream<int> input) async* {
var total = 0;
await for (final value in input) {
total += value;
yield total;
}
}
Future<void> main() async {
final deposits = Stream.fromIterable([100, 50, 25, 200]);
print(await runningTotal(deposits).toList());
}[100, 150, 175, 375]
Tip: The
rxdartandstream_transformpackages add operators such asdebounce,throttle,combineLatestandswitchMap— handy for search boxes and reactive UIs.
Test yourself
Which method maps each event through a function that returns a Future?
- map
- asyncMap
- expand
- then
What does distinct() remove?
- All duplicate values ever seen
- Consecutive duplicate events
- Null events
- Error events
What type does stream.toList() return?
- List<T>
- Future<List<T>>
- Stream<List<T>>
- Iterable<T>