Summary - Streams
- Dart course
- Intermediate
- Lesson 69/116
- 5 min
Combine listen, map and StreamController to write an event logger.
Summary - Streams
In this group we learned the basics of Streams: Stream represents an event sequence; listen subscribes; map/where transforms; asyncExpand expands; StreamController creates manually.
Together these tools form the foundation of event-driven programming in Dart. They are used for user input, sensor data, network packets and other continuously flowing data.
Now let's do an exercise that uses two tools together: produce events with StreamController, transform with map and print.
Practice Produce with controller, transform with map
import 'dart:async' is already added. void main() async is already written. Create a StreamController<int>(). Send two events with controller.add(10) and controller.add(20). Close with controller.close(). Double events with controller.stream.map((n) => n * 2). Listen with await for and print with print.
Starter code
import 'dart:async';
void main() async {
// create a StreamController<int>, add two values, close
// double with .map, print with await for
}Sample solution
import 'dart:async';
void main() async {
var controller = StreamController<int>();
controller.add(10);
controller.add(20);
controller.close();
var doubled = controller.stream.map((n) => n * 2);
await for (var n in doubled) {
print(n);
}
}Expected output
20 40
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the stream concepts
| Term | Meaning |
|---|---|
Stream |
Event sequence |
listen |
Subscribe |
map/where |
Transform |
StreamController |
Manual creation |
2 Which class lets you create your own Stream manually?
- StreamController Correct answer
- Completer
- Future
- Iterable
Explanation: StreamController lets you create your own Stream manually.