Back to results for “Fundamentals”
Flutter › Dart Streams & StreamControllers

How does the StreamBuilder widget in Flutter let you build a reactive user interface that automatically updates whenever a Stream emits a new value, without needing to manually manage the underlying subscription yourself?

Advanced

Answer

The StreamBuilder widget handles subscribing to a provided Stream, automatically rebuilding its child widget tree every single time that stream emits a brand new value, and automatically and properly cancelling the underlying subscription whenever the StreamBuilder widget itself is eventually removed from the widget tree, meaning you never need to manually manage the stream subscription's entire lifecycle yourself, which significantly reduces the risk of forgetting to properly cancel a subscription and thereby accidentally causing a memory leak.
StreamBuilder<int>(
  stream: countStream(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) return CircularProgressIndicator();
    return Text('Count: ${snapshot.data}');
  },
)
Real-world example A live auction app uses a StreamBuilder to automatically display the current highest bid the very instant it changes, without ever needing to manually manage subscribing to or cancelling the underlying bid update stream itself.

Common follow-ups: What does the ConnectionState value within a StreamBuilder's snapshot actually represent?;What happens if the Stream instance passed to a StreamBuilder is accidentally recreated on every single rebuild?