Dart Stream
Stream is Dart's mechanism for handling sequences of continuous asynchronous events.
If a Future is a one-time asynchronous result, then a Stream is a continuous, ongoing flow of asynchronous data delivered multiple times.
This chapter introduces the concept of Stream, listening with await for, creating Streams with StreamController, and the difference between single-subscription and broadcast Streams.
Stream and event sequences
A Stream is like a conveyor belt: data arrives one by one over time.
You don't need to wait for all the data at once; instead, you process each item as it arrives.
Typical use cases for Stream:
| Scenario | Example |
|---|---|
| User input events | Button clicks, mouse movements, keyboard input |
| File reading | Reading a large file line by line |
| Network data | WebSocket messages, real-time APIs |
| Timer | A timed event triggered once per second |
| State changes | State management Streams in Flutter |
Example
Basic use of Stream -- listening with listen:
void
main
(
)
{
// Create a Stream: emit a number every 1 second
var
stream
=
Stream
<
int
.
periodic
(
Duration
(
seconds
:
1
)
,
(
count
)
=>
count
1
,
// count starts from 0
)
;
(
'Start listening to Stream...'
)
;
// listen subscribes to the Stream
var
subscription
=
stream.
listen
(
(
data
)
{
// Called whenever new data arrives
(
'RUNOOB received data: $data'
)
;
}
,
onError
:
(
error
)
{
// Called when the Stream encounters an error
(
'Error: $error'
)
;
}
,
onDone
:
(
)
{
// Called when the Stream closes
(
'Stream closed'
)
;
}
,
)
;
// Cancel the subscription after 5 seconds
Future.
delayed
(
Duration
(
seconds
:
5
)
,
(
)
{
subscription.
cancel
(
)
;
(
'Subscription cancelled'
)
;
}
)
;
}
开始监听 Stream...
RUNOOB 收到数据: 1
RUNOOB 收到数据: 2
RUNOOB 收到数据: 3
RUNOOB 收到数据: 4
RUNOOB 收到数据: 5
已取消订阅
listen() returns a StreamSubscription object that you can use to control the subscription:
| Method | Purpose |
|---|---|
| subscription.pause() | Pause receiving data |
| subscription.resume() | Resume receiving data |
| subscription.cancel() | Cancel the subscription |
| subscription.isPaused | Whether it is paused |
Listening with await for
Besides the listen() callback approach, you can also use an await for loop to consume a Stream.
await for makes Stream handling logic as clear as a regular for loop.
Example
// Generate a finite data stream
Stream
<
int
countStream
(
int
max
)
async
{
for
(
int
i
=
1;
i
<=
max
;
i
++
)
{
await Future.
delayed
(
Duration
(
milliseconds
:
300
)
)
;
yield i
;
// yield emits data into the Stream
}
}
Future
<
void
main
(
)
async
{
print
('Start consuming Stream with await for...'
)
;
// await for: wait for each data item to arrive and process them one by one
await
for
(
var
value
in
countStream
(
5
)
)
{
(
'RUNOOB count: $value'
)
;
}
(
'Stream consumption complete'
)
;
}
开始用 await for 消费 Stream...
RUNOOB 计数: 1
RUNOOB 计数: 2
RUNOOB 计数: 3
RUNOOB 计数: 4
RUNOOB 计数: 5
Stream 消费完毕
Features of await for:
- Similar in form to a regular for loop, but each iteration waits for the next data item to arrive
- The loop ends automatically when the Stream closes
- Can only be used inside async functions
- To exit midway, use break (same as a regular for loop)
await for suits scenarios "where all data must be processed in order", such as reading all lines of a file. listen() suits scenarios "that require continuous response to events", such as button clicks. The two can replace each other, but each has its own strengths.
Creating Streams with StreamController
StreamController is a tool for manually creating and controlling a Stream.
You can add data or errors to it, or close it, at any time.
Example
import
'dart:async'
;
// Use StreamController to implement a simple countdown timer
class
CountdownTimer
{
final
StreamController
<
int
_controller
=
StreamController
<
int
(
);
Timer
?
_timer
;
int
_remaining
=
0
;
// Expose the Stream for external subscription
Stream
<
int
get
tickStream
=>_controller.
stream
;
// Start the countdown
void
start
(
int
seconds
)
{
_remaining
=
seconds
;
// Send the initial value immediately
_controller.
add
(
_remaining
)
;
_timer
=
Timer.
periodic
(
Duration
(
seconds
:
1
)
,
(
timer
)
{
_remaining
--
;
if
(
_remaining
0
)
{
_controller.
add
(
_remaining
)
;
// Send data
}
else
{
_controller.
add
(
0
)
;
// Send the final 0
_controller.
close
(
)
;
// Close the Stream
timer.
cancel
(
)
;
}
}
)
;
}
// Cancel the countdown
void
cancel
(
)
{
_timer
?
.
cancel
(
)
;
_controller.
addError
(
'Countdown cancelled'
)
;
// Send an error
_controller.
close
(
)
;
}
// Release resources
void
dispose
(
)
{
_controller.
close
(
)
;
}
}
Future
<
void
main
(
)
async
{
var
timer
=
CountdownTimer
(
);
// Subscribe to countdown events
timer.
tickStream
.
listen
(
(
remaining
)
{
(
'RUNOOB countdown: $remaining seconds'
)
;
}
,
onError
:
(
error
)
{
(
'Error: $error'
)
;
}
,
onDone
:
(
)
{
(
'Countdown finished!'
)
;
}
,
)
;
timer.
start
(
5
)
;
// Wait for the countdown to complete
await Future.
delayed
(
Duration
(
seconds
:
6
)
)
;
timer.
dispose
(
)
;
}
RUNOOB 倒计时: 5 秒
RUNOOB 倒计时: 4 秒
RUNOOB 倒计时: 3 秒
RUNOOB 倒计时: 2 秒
RUNOOB 倒计时: 1 秒
RUNOOB 倒计时: 0 秒
倒计时结束!
async* generator functions
If you only need to simply generate a sequence of data, async* is more convenient than StreamController.
Example
// async* marks this as an asynchronous generator function
// The return type must be Stream
Stream
<
String
readLinesAsync
(
)
async
{
var
lines
=
['First line'
,
'Second line'
,
'Third line'
,
'RUNOOB'
]
;
for
(
var
line
in
lines
)
{
await Future.
delayed
(
Duration
(
milliseconds
:
500
)
)
;
yield line
;
// yield emits data into the Stream
}
// The Stream closes automatically when the function ends
}
// Asynchronous generator with error handling
Stream
<
int
generateNumbersWithError
(
)
async
{
for
(
int
i
=
1;
i
<=
5
;
i
++
)
{
await Future.
delayed
(
Duration
(
milliseconds
:
300
)
)
;
if
(
i
==
3
)
{
throw
Exception
(
'Number 3 has an error!'
)
;
}
yield i
;
}
}
Future
<
void
main
(
)
async
{
print
('Reading line by line:'
)
;
await
for
(
var
line
in
readLinesAsync
(
)
)
{
(
' $line'
)
;
}
(
'\nGenerator with errors:'
)
;
try
{
await
for
(
var
num
in
generateNumbersWithError
(
)
)
{
(
' Number: $num'
)
;
}
}
catch
(
e
)
{
(
' Caught error: $e'
)
;
}
}
Read line by line:
第一行
第二行
第三行
RUNOOB
Generator with errors:
数字: 1
数字: 2
捕获错误: Exception: 数字 3 出错了!
Single-subscription vs broadcast Streams
Dart's Streams come in two types: single-subscription Streams (Single-subscription) and broadcast Streams (Broadcast).
Single-subscription Stream
This is the default Stream type.
It can only be subscribed to by one listener, suitable for scenarios "consumed once from start to finish".
Example
void
main
(
)
{
// Single-subscription Stream (default)
var
stream
=
Stream.
fromIterable
(
[
1
,
2
,
3
]
)
;
// First subscription: OK
stream.
listen
(
(
data
)
=>
(
'Subscriber 1: $data'
)
)
;
// Second subscription: error! A single-subscription Stream cannot be subscribed to multiple times
// stream.listen((data) => print('Subscriber 2: $data')); // Runtime error
}
Broadcast Stream
Broadcast Streams allow multiple listeners to subscribe simultaneously, suitable for event broadcasting scenarios.
Example
import
'dart:async'
;
void
main
(
)
{
// Create a broadcast Stream
var
controller
=
StreamController
<
int
.
broadcast
(
)
;
// Multiple subscribers can listen at the same time
controller.
stream
.
listen
(
(
data
)
=>
(
'RUNOOB Subscriber A: received $data'
)
,
)
;
controller.
stream
.
listen
(
(
data
)
=>
(
'RUNOOB Subscriber B: received $data'
)
,
)
;
// Send data; both subscribers will receive it
controller.
add
(
1
)
;
controller.
add
(
2
)
;
controller.
add
(
3
)
;
// Late subscribers can also receive subsequent data (but not earlier data)
Future.
delayed
(
Duration
(
seconds
:
1
)
,
(
)
{
controller.
stream
.
listen
(
(
data
)
=>
(
'RUNOOB Late Subscriber C: received $data'
)
,
)
;
controller.
add
(
4
)
;
controller.
close
(
)
;
}
)
;
}
RUNOOB 订阅者A: 收到 1
RUNOOB 订阅者B: 收到 1
RUNOOB 订阅者A: 收到 2
RUNOOB 订阅者B: 收到 2
RUNOOB 订阅者A: 收到 3
RUNOOB 订阅者B: 收到 3
RUNOOB 订阅者A: 收到 4
RUNOOB 订阅者B: 收到 4
RUNOOB 迟到的订阅者C: 收到 4
Comparison of the two Stream types:
| Feature | Single-subscription Stream | Broadcast Stream |
|---|---|---|
| Number of subscribers | Only one | Can be multiple |
| Data replay | Consume from the beginning | Only receive data after subscribing |
| Typical scenario | File reading, HTTP responses | Button clicks, state notifications |
| Creation method | StreamController() | StreamController.broadcast() |
A broadcast Stream's "late subscribers" can only receive events after subscribing; earlier events have already been missed. This is the most important behavioral difference between broadcast and single-subscription Streams.
Common Stream transformation methods
Stream provides a series of methods to transform and process data, similar to List's functional methods.
Example
void
main
(
)
async
{
var
numbers
=
Stream.
fromIterable
(
[
1
,
2
,
3
,
4
,
5
,
6
]
)
;
// map: transform each data item
var
doubled
=
numbers.
map
(
(
n
)
=>
n
2
)
;
(
'Doubled:'
)
;
await
for
(
var
n
in
doubled
)
{
(
' $n'
)
;
}
// where: filter data
var
source
=
Stream.
fromIterable
(
[
10
,
15
,
20
,
25
,
30
]
)
;
var
even
=
source.
where
(
(
n
)
=>
n
%
2
==
0
)
;
(
'Even numbers:'
)
;
await
for
(
var
n
in
even
)
{
(
' $n'
)
;
}
// take: take only the first N
var
infinite
=
Stream.
periodic
(
Duration
(
milliseconds
:
100
)
,
(
i
)
=>
i
1
,
)
;
(
'Take only the first 3:'
)
;
await
for
(
var
n
in
infinite.
take
(
3
)
)
{
(
' RUNOOB: $n'
)
;
}
// skip: skip the first N
var
data
=
Stream.
fromIterable
(
[
1
,
2
,
3
,
4
,
5
]
)
;
(
'Skip the first 2:'
)
;
await
for
(
var
n
in
data.
skip
(
2
)
)
{
(
' $n'
)
;
}
// distinct: remove duplicates
var
duplicates
=
Stream.
fromIterable
(
[
1
,
2
,
2
,
3
,
3
,
3
]
)
;
(
'Deduplicated:'
)
;
await
for
(
var
n
in
duplicates.
distinct
(
)
)
{
(
' $n'
)
;
}
}
翻倍:
2
4
6
8
10
12
偶数:
10
20
30
# Take the first 3:
RUNOOB: 1
RUNOOB: 2
RUNOOB: 3
Skip the first 2:
3
4
5
去重:
1
2
3