Sub topic 3
Rendering a Stream with StreamBuilder
This chapter assumes you know Dart's async, await, and Future, can write a StatefulWidget with setState, and understand initState and dispose.
Streams deliver many values
A Stream delivers a sequence of values over time, while a Future delivers one value. StreamBuilder subscribes to a stream and calls its builder each time an event arrives. The snapshot.data field holds the latest event, and snapshot.connectionState reports whether the stream is waiting, active, or done.
import 'dart:async';
import 'package:flutter/material.dart';
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();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
StreamBuilder<int>(
stream: _controller.stream,
initialData: 0,
builder: (context, snapshot) => Text('Count: ${snapshot.data}'),
),
ElevatedButton(
onPressed: () => _controller.add(++_count),
child: const Text('Increment'),
),
],
);
}
}Showing something before the first event with initialData
Before the first event arrives, snapshot.data is null unless you pass initialData. The value you pass fills snapshot.data on the first frame, so the widget can show something useful right away. The connectionState stays waiting until the first real event.
Single-subscription and broadcast streams, and closing a StreamController
A single-subscription stream accepts one listener. A broadcast stream accepts many. Use StreamController.broadcast() when more than one widget listens to the same stream.
Close the controller in dispose. An open controller keeps its resources alive after the widget is gone.
Testing FutureBuilder and StreamBuilder widgets
Use testWidgets with a controller that the test owns. Add an event, then call tester.pump() so the widget rebuilds.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('shows the latest stream value', (tester) async {
final controller = StreamController<int>.broadcast();
addTearDown(controller.close);
await tester.pumpWidget(MaterialApp(
home: StreamBuilder<int>(
stream: controller.stream,
initialData: 0,
builder: (context, snapshot) => Text('Count: ${snapshot.data}'),
),
));
expect(find.text('Count: 0'), findsOneWidget);
controller.add(5);
await tester.pump();
expect(find.text('Count: 5'), findsOneWidget);
});
}When builders are not enough
Builders suit one widget that reads one async source. Move the logic into a state management solution such as Provider, Riverpod, or BLoC when several screens share the same data, when you combine or cache streams, or when you want to test business logic without building widgets.
Exercise
What happens if the StreamBuilder in the example uses a single-subscription controller and a second widget also listens to its stream?
Show answer
The second listen throws a StateError. Create the controller with StreamController.broadcast() so that several listeners can subscribe.