Flutter › Dart Streams & StreamControllers

What is the difference between a single subscription stream and a broadcast stream in Dart, and when would you specifically need to use a broadcast stream instead?

Intermediate

Answer

A single subscription stream, which is the default type created by a regular StreamController, only allows exactly one single listener to ever subscribe to it over its entire lifetime, and attempting to add a second separate listener throws an error, whereas a broadcast stream, created by passing the broadcast parameter, allows multiple entirely separate listeners to all subscribe to and independently receive the exact same stream of events simultaneously, which is necessary whenever more than one distinct part of your application genuinely needs to react to the very same underlying stream of events at the same time.
final controller = StreamController<String>.broadcast();

controller.stream.listen((value) => print('Listener 1: $value'));
controller.stream.listen((value) => print('Listener 2: $value'));
Real-world example A shared notification service uses a broadcast StreamController so that both the main notification badge indicator and a separate dedicated notifications screen can each independently listen to and react to the exact same underlying stream of incoming notification events.

Common follow-ups: What error occurs if you try to add a second listener to a non broadcast stream?;Can a single subscription stream ever be converted into a broadcast stream afterward?