Sub topic 10
Single-subscription and broadcast streams, and closing a StreamController
This chapter assumes you know Dart async and await, Flutter widgets, StatefulWidget, setState, initState, dispose, and the basic use of StreamBuilder.
A stream is an asynchronous sequence of values. A Future completes once. A stream can emit many values, then finish with a done event or remain open. A StreamController is an object that lets your code add values, errors, and a done event to a stream.
Single-subscription streams
A single-subscription stream allows only one listener during its lifetime. This is the default kind of stream created by StreamController.
Single-subscription streams suit one consumer, such as one screen reading a file or one service processing a response. If a second part of the program tries to listen, Dart throws a StateError.
A StreamBuilder normally creates and manages one subscription to its stream. Therefore, passing the same single-subscription stream to two StreamBuilder widgets is invalid.
Broadcast streams
A broadcast stream allows multiple listeners at the same time. Create one with StreamController.broadcast().
Broadcast streams suit events that several widgets may observe, such as authentication changes, connectivity updates, or an application-wide notification. Each active listener receives events independently.
A broadcast stream does not replay old events to a new listener. If no listener is active when an event is added, that event is usually lost. Use stored state or another stream type when new listeners must receive the latest value.
| Stream type | Listeners | Best fit | Important behavior |
|---|---|---|---|
| Single-subscription | One | One consumer or one operation | A second listener fails |
| Broadcast | Many | Shared events | New listeners do not receive old events |
Managing a controller's lifecycle
A controller owns resources connected to its stream. When a State object creates a controller, the State object should close it in dispose.
Closing a controller sends the stream's done event. It also releases resources used by the controller. After close() starts, do not call add() or addError().
Create the controller once, not inside build. The following widget uses a broadcast controller so that more than one widget could listen to its stream. The example itself has one StreamBuilder, but the stream type allows future listeners.
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: CounterPanel()));
}
class CounterPanel extends StatefulWidget {
const CounterPanel({super.key});
@override
State<CounterPanel> createState() => _CounterPanelState();
}
class _CounterPanelState extends State<CounterPanel> {
final StreamController<int> _controller =
StreamController<int>.broadcast();
int _count = 0;
@override
void dispose() {
_controller.close();
super.dispose();
}
void _increment() {
if (!_controller.isClosed) {
_controller.add(++_count);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Stream controller')),
body: Center(
child: StreamBuilder<int>(
stream: _controller.stream,
initialData: 0,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.done) {
return const Text('Finished');
}
return Text('Count: ${snapshot.data}');
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: _increment,
child: const Icon(Icons.add),
),
);
}
}The StreamBuilder subscribes when it receives the stream and cancels its subscription when the widget leaves the tree. The controller itself belongs to _CounterPanelState, so that state closes it in dispose.
The isClosed check is useful when another asynchronous callback might try to add an event while the widget is being removed. In many simple widgets, lifecycle control already prevents that callback. The check is still a safe boundary before publishing an event.
Common lifecycle errors
- Creating a controller in
buildcreates a new stream on every rebuild. - Forgetting
close()can keep subscriptions or other resources alive. - Using a single-subscription stream with multiple listeners causes a runtime error.
- Assuming broadcast streams replay values leads to missing initial state.
- Calling
add()afterclose()causes an error.
Choose the stream type based on ownership and listener needs. Choose a StreamController only when your code must actively publish events. If a repository already exposes the stream, let that repository manage its lifecycle.
Exercise
A StatefulWidget creates a StreamController in initState, and its StreamBuilder is removed from the widget tree. Should the widget close the controller in dispose?
Show answer
Yes, if the widget owns the controller. Call _controller.close() in dispose, then call super.dispose().