Sobes.tech
Middle

How are streams used in Flutter?

sobes.tech AI

Answer from AI

Streams in Flutter are used for working with a sequence of asynchronous events. They are based on reactive programming paradigms and provide a way to process data as it arrives.

Main uses of streams:

  • UI updates: Listening to data changes (e.g., from network requests or databases) and automatically updating widgets.
  • Communication between BLoC/Cubit and UI: BLoC/Cubit use Stream (via StateStreamable) to emit states that the UI subscribes to.
  • Handling user input: Tracking input events (e.g., from text fields).
  • Working with WebSocket and other asynchronous operations: Receiving data in real-time.

Main concepts:

  • Stream: A sequence of asynchronous events.
  • StreamController: Manages a stream, allows adding data (add), errors (addError), and closing the stream (close).
  • StreamSubscription: An object representing an active subscription to a stream. It allows receiving data (onData), handling errors (onError), and stream completion (onDone).

Example of using with StreamBuilder:

// Suppose we have a stream that emits integers
Stream<int> countStream = Stream.periodic(Duration(seconds: 1), (count) => count);

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<int>(
      stream: countStream, // Subscribing to the stream
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator(); // While waiting for data
        } else if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}'); // If an error occurred
        } else {
          return Text('Count: ${snapshot.data}'); // Displaying the latest data from the stream
        }
      },
    );
  }
}

Streams can be:

  • Single-subscription: Only one listener can be subscribed at any time. Attempting to subscribe a second time will cause an error.
  • Broadcast: Multiple listeners can subscribe to the same stream. Data is sent to all active listeners.

To handle streams, operators from the rxdart package are often used, providing a rich set of utilities for transforming, filtering, and combining streams.