Sobes.tech
Junior

What are streams used for in Flutter?

sobes.tech AI

Answer from AI

Streams in Flutter are used for handling sequences of asynchronous events.

Main use cases:

  1. Responding to data changes: Redux, BLoC patterns use streams to manage application state and reactively update the UI when changes occur.
  2. Working with streaming data: Receiving data over the network (e.g., WebSocket), reading from files, working with device sensors.
  3. Handling user interactions: Tracking scrolling, Draggable / DragTarget.
  4. Asynchronous operations: Performing tasks in the background and receiving results as they become available.

Key concepts:

  • Stream: A sequence of asynchronous events. A stream can emit 0 or more events and then close (successfully or with an error).
  • StreamSubscription: Represents a subscription to a stream. Allows receiving events from the stream and managing the subscription (pause, resume, cancel).
  • Sink: Used to add data to a stream.
  • StreamBuilder: A widget that rebuilds when new data is received from the stream.
// Example of using StreamBuilder
StreamBuilder<int>(
  stream: counterStream, // Your stream
  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
    if (snapshot.hasError) {
      return Text('Error: \\${snapshot.error}');
    }
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return Text('Waiting...');
      case ConnectionState.waiting:
        return CircularProgressIndicator();
      case ConnectionState.active:
        return Text('Value: \\${snapshot.data}');
      case ConnectionState.done:
        return Text('Stream closed. Last value: \\${snapshot.data}');
    }
  },
)
// Example of a simple stream that emits numbers
Stream<int> countStream(int max) async* {
  for (int i = 0; i <= max; i++) {
    await Future.delayed(Duration(seconds: 1));
    yield i; // Emit value
  }
}
What are streams used for in Flutter? — Flutter - sobes.tech