Flutter Streams and StreamBuilder

A Future delivers one value at some point later. A Stream delivers many values over time. Think of a Future as a package that arrives once, and a Stream as a water pipe that keeps delivering. Chat messages, live sports scores, location updates, and countdown timers all arrive as streams.

Future and Stream Side by Side


  Future:   ──────────────● (one value, done)

  Stream:   ──●────●──●────────●───●──── (many values over time)
              1    2  3        4   5
TypeValuesExample
FutureOneDownload a profile
StreamZero or manyReceive chat messages

Creating a Stream with async*

A function marked async* produces a stream. The yield keyword sends each value into the pipe.


Stream<int> countDown(int from) async* {
  for (int i = from; i >= 0; i--) {
    await Future.delayed(Duration(seconds: 1));
    yield i;
  }
}

This function emits 5, 4, 3, 2, 1, 0 with a one-second pause between values.

Listening to a Stream

The listen method attaches a handler that runs for every value.


final subscription = countDown(5).listen(
  (value) {
    print('Tick: $value');
  },
  onDone: () {
    print('Finished');
  },
  onError: (error) {
    print('Problem: $error');
  },
);

// Stop listening
subscription.cancel();

A StreamSubscription object represents the connection. Cancel it when the screen closes, or the app keeps work running that nobody needs.

Stream.periodic

This built-in helper emits a value on a fixed schedule. A clock widget uses it.


Stream<DateTime> clock = Stream.periodic(
  Duration(seconds: 1),
  (count) => DateTime.now(),
);

StreamController

A StreamController lets your own code push values into a stream whenever you want. Picture a funnel: you pour water in at the top, and listeners collect it at the bottom.


final controller = StreamController<String>();

controller.sink.add('Hello');
controller.sink.add('Welcome');

controller.stream.listen((message) {
  print(message);
});

// Close when finished
controller.close();

  add('Hello') ──┐
                 ▼
            ┌─────────┐
            │ Sink    │  ← input end
            │ Stream  │  ← output end
            └────┬────┘
                 ▼
            listeners

Single and Broadcast Streams

A normal stream allows one listener. Create a broadcast stream when several widgets need the same data.


final controller = StreamController<int>.broadcast();

StreamBuilder: Streams in the UI

StreamBuilder listens to a stream and rebuilds its child on every new value. The widget cancels the subscription for you.


StreamBuilder<int>(
  stream: countDown(10),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator();
    }
    if (snapshot.hasError) {
      return Text('Error: ${snapshot.error}');
    }
    if (!snapshot.hasData) {
      return Text('No data');
    }
    return Text('${snapshot.data}', style: TextStyle(fontSize: 48));
  },
)

The AsyncSnapshot Object

The snapshot holds the latest information about the stream.

PropertyMeaning
connectionStatenone, waiting, active, or done
hasDataTrue when a value arrived
dataThe newest value
hasErrorTrue when the stream reported a failure
errorThe failure details

Create the Stream Once

A common mistake builds the stream inside the build method. Each rebuild creates a fresh stream and restarts it. Store the stream in a variable inside initState instead.


class _TimerState extends State<TimerScreen> {
  late Stream<int> _stream;

  @override
  void initState() {
    super.initState();
    _stream = countDown(10);
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<int>(stream: _stream, builder: (context, snapshot) {
      return Text('${snapshot.data ?? 10}');
    });
  }
}

Real Examples of Streams

  • Firebase Firestore sends live document changes as a stream.
  • Location packages emit a position stream while the user moves.
  • Web socket connections stream messages from a server.
  • Text field controllers notify listeners on every keystroke.

Transforming Streams

Streams offer methods similar to lists: map, where, and take.


countDown(10)
    .where((n) => n % 2 == 0)
    .map((n) => 'Even: $n')
    .listen(print);

Practice Ideas

Build a stopwatch that uses Stream.periodic and displays the elapsed seconds through a StreamBuilder. Add a start and a stop button that pause the subscription. Build a second screen with a StreamController that sends typed messages into a list, imitating a chat room.

Choosing Between Future and Stream

Ask one question: does the answer arrive once or keep arriving? A login request returns one result, so a Future fits. A chat room delivers messages all day, so a Stream fits. Using a Stream for a one-time answer adds needless complexity, and using a Future for live updates forces you to ask again and again. Matching the tool to the shape of the data keeps the code short and the screen responsive.

Handling Errors in Streams

A stream can deliver an error and keep running, or stop after one. The onError callback of listen catches failures, and the hasError flag on a snapshot reports them to the screen. Show a retry button in the error state, and recreate the stream when the user taps it. Planning for the error path keeps live screens friendly when connections drop.