Dart Streams
Dart Streams
A future gives you one value later.
A Stream gives you many values, one after another, over time.
You can think of a stream like a conveyor belt at an airport: the bags arrive one at a time, and you take each bag when it comes.
Each value that a stream sends is called an event.
Streams are used for things like clicks in an app, messages in a chat, or data that is read from a file in small parts.
Read a Stream With await for
Stream.fromIterable() creates a stream from a list.
The await for loop waits for each event and runs the loop body once for every value.
Like await, it can only be used inside an async function:
Example
Future<void> main() async {
Stream<String> bags = Stream.fromIterable(['Red bag', 'Blue bag', 'Black bag']);
await for (String bag in bags) {
print('Picked up: $bag');
}
print('All bags picked up');
}
Try it Yourself »
Result:
Picked up: Red bag
Picked up: Blue bag
Picked up: Black bag
All bags picked up
The loop ends when the stream is finished (Dart says the stream is done), and then the code after the loop runs.
Values Over Time
Stream.periodic() creates a stream that sends a new event every time a period of time has passed.
The function you give it gets a counter that starts at 0.
A periodic stream never stops by itself, so use take() to keep only the first few events:
Example
Future<void> main() async {
Stream<int> countdown = Stream.periodic(Duration(seconds: 1), (i) => 3 - i).take(3);
await for (int number in countdown) {
print(number);
}
print('Liftoff!');
}
Try it Yourself »
Result:
3
2
1
Liftoff!
Each number was printed one second after the one before it.
The listen() Method
Another way to read a stream is the listen() method.
It runs a function for each event, and it does not need an async function.
The optional onDone function runs when the stream is finished:
Example
void main() {
Stream<int> scores = Stream.fromIterable([70, 85, 92]);
scores.listen(
(score) {
print('New score: $score');
},
onDone: () {
print('No more scores');
},
);
print('Listening...');
}
Try it Yourself »
Result:
Listening...
New score: 70
New score: 85
New score: 92
No more scores
Notice that Listening... is printed first.
listen() does not wait, just like then() on a future.
Change a Stream With map() and where()
Streams have methods like the ones you know from lists.
map()changes every event into a new value.where()keeps only the events that pass a test.
Each method returns a new stream:
Example
Future<void> main() async {
Stream<int> prices = Stream.fromIterable([5, 12, 3, 20, 8]);
Stream<String> labels = prices
.where((price) => price >= 8)
.map((price) => 'Price: $price dollars');
await for (String label in labels) {
print(label);
}
}
Try it Yourself »
Result:
Price: 12 dollars
Price: 20 dollars
Price: 8 dollars
StreamController
A StreamController lets you make a stream and send events into it yourself.
It comes from the dart:async library, so you must import it at the top of the file.
controller.streamis the stream that others can listen to.controller.add()sends a new event.controller.close()tells the listeners that there are no more events.
Example
import 'dart:async';
void main() {
final controller = StreamController<String>();
controller.stream.listen(
(message) {
print('New message: $message');
},
onDone: () {
print('Chat closed');
},
);
controller.add('Hi!');
controller.add('How are you?');
controller.add('See you later');
controller.close();
}
Try it Yourself »
Result:
New message: Hi!
New message: How are you?
New message: See you later
Chat closed
Note: The stream of a normal StreamController can only have one listener.
If you call listen() on it a second time, Dart throws an error: Bad state: Stream has already been listened to.