Google News
logo
Flutter - Interview Questions
What is a Stream in Dart and how is it used in Flutter?
In Dart, a Stream is a sequence of asynchronous events that can be listened to and handled by listeners. A Stream can emit values of any data type, including custom classes, and can be used to represent a variety of asynchronous operations, such as network requests, file I/O, and user input.

In Flutter, Streams are commonly used to handle real-time data updates, such as updating the UI when new data is available from a network or database. Flutter provides several built-in widgets, such as `StreamBuilder`, that can be used to listen to a Stream and rebuild the UI automatically when new data is received.

Here's an example of a basic Stream in Dart that emits a sequence of integers :
import 'dart:async';

void main() {
  final stream = Stream<int>.periodic(Duration(seconds: 1), (count) => count).take(5);

  stream.listen((value) => print(value), onError: (error) => print(error), onDone: () => print('Done!'));
}​
In this example, we create a Stream that emits a sequence of integers using the `Stream.periodic()` constructor. The first argument to `Stream.periodic()` is a `Duration` object that specifies the interval between emitted values, and the second argument is a function that produces the values to emit. The `take()` method is used to limit the number of values emitted by the Stream to 5.

We then listen to the Stream using the `listen()` method, which takes three optional parameters: a callback function to handle each emitted value, a callback function to handle errors, and a callback function to handle when the Stream is done emitting values.

In Flutter, we can use the `StreamBuilder` widget to build a UI that responds to real-time updates from a Stream. The `StreamBuilder` takes a Stream as input and rebuilds the UI automatically whenever a new event is emitted by the Stream. This allows us to create reactive UIs that update in real-time based on data changes.
Advertisement