Stream transformation
- Dart course
- Intermediate
- Lesson 66/116
- 5 min
Learn stream transformation with map and where.
Stream transformation
Streams can be transformed with map and where. map transforms each event; where lets through events that match a condition. These methods return a new Stream.
Example: var filtered = stream.where((n) => n.isEven);. This lets only even number events through. var doubled = filtered.map((n) => n * 2); doubles each event.
To listen to the transformed Stream you use await for. Chaining is possible: stream.where(...).map(...). Each transform is lazy.
Chaining transforms
Stream transforms can be chained. Writing stream.where(...).map(...) you do multiple transforms in one flow. Each transform feeds the next.
Example: on a [1, 2, 3, 4] stream first where keeps evens (2, 4), then map doubles them (4, 8). Result: 4, 8. You listen with await for.
Chaining is a readable way to process data step by step. Each step has one responsibility; the code stays clear.
Practice Filter and transform a Stream
void main() async is already written. Stream.fromIterable([1, 2, 3, 4]) is already created. First filter evens with .where((n) => n.isEven), then double with .map((n) => n * 2). Listen to the result with await for and print with print.
Starter code
void main() async {
var stream = Stream.fromIterable([1, 2, 3, 4]);
// filter evens with .where, double with .map, print with await for
}Sample solution
void main() async {
var stream = Stream.fromIterable([1, 2, 3, 4]);
var filtered = stream.where((n) => n.isEven);
var doubled = filtered.map((n) => n * 2);
await for (var n in doubled) {
print(n);
}
}Expected output
4 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the transform methods
| Term | Meaning |
|---|---|
.where((n) => n.isEven) |
Filter evens |
.map((n) => n * 2) |
Double |
await for |
Listen to result |
print(n) |
Print event |
2 What does stream.where(...) return?
var s = Stream.fromIterable([1, 2, 3]);
var f = s.where((n) => n.isEven);- A list
- A new Stream Correct answer
- A Future
- void
Explanation: where returns a new Stream.
3 The map call
var filtered = stream.where((n) => n.isEven);
var doubled = filtered.____((n) => n * 2);
var filtered = stream.where((n) => n.isEven);
var doubled = filtered.map((n) => n * 2);
Explanation: map transforms each event.