D
State ManagementIntermediate30 XP4 min read

How are Dart Streams used in state management?

TL;DR: Streams deliver asynchronous sequences of values. In state management, StreamController emits state changes. BLoC is built on streams. StreamBuilder or ref.watch(streamProvider) subscribe to them in the UI.

Full Answer

Dart's Stream API is the foundation of BLoC state management. Understanding streams is key to understanding how BLoC works internally.

  • StreamController<T> — creates a single-subscription stream
  • StreamController.broadcast() — supports multiple listeners
  • StreamBuilder — rebuilds widget on each stream event
  • BehaviorSubject (RxDart) — like broadcast + replays latest value to new subscribers
  • StreamSubscription — handle returned from stream.listen(); cancel in dispose()
🎯

Always cancel StreamSubscriptions in dispose(). Uncancelled subscriptions cause memory leaks and 'setState called after dispose' errors.

Code Examples

dartStreamBuilder with a stream
Output
StreamBuilder rebuilds with 'Count: 1', 'Count: 2', etc. on each increment() call

Common Mistakes

  • Using a single-subscription StreamController with multiple StreamBuilders — second subscriber throws
  • Not closing StreamControllers — causes 'Stream has been closed' errors

Interview Tip

💡

Tracing BLoC back to Dart streams shows you understand the foundations, not just the library API.

#Stream#StreamController#BehaviorSubject#RxDart