In Dart, futures and streams are fundamental concepts used for asynchronous programming. They provide a way to handle operations that may not immediately return a result, such as network requests, file I/O, or computations that take time to complete.
Futures:
- Definition: A future represents a potential value or error that will be available at some point in the future.
- Usage: Futures are typically used to represent a single asynchronous operation. You can create a future using the
Future
class, and it can complete with either a value or an error. - Methods: Futures provide methods to handle completion, such as
then
,catchError
, andwhenComplete
. These methods allow you to specify what to do when the future completes with a value or an error. - Example:
1234567891011Future<int> fetchUserData() {return Future.delayed(Duration(seconds: 2), () => 42);}void main() {fetchUserData().then((value) {print('User data fetched: $value');}).catchError((error) {print('Error fetching user data: $error');});}
Streams:
- Definition: A stream is a sequence of asynchronous events over time. It allows you to handle a continuous flow of data, such as user input, sensor data, or data from network sockets.
- Usage: Streams are used to represent ongoing asynchronous operations where multiple values are emitted over time. You can create a stream using the
Stream
class, and it can emit values or errors asynchronously. - Methods: Streams provide methods to handle events, such as
listen
,map
,where
, andreduce
. These methods allow you to transform, filter, and combine stream events. - Example:
1234567891011Stream<int> counterStream() async* {for (int i = 1; i <= 5; i++) {await Future.delayed(Duration(seconds: 1));yield i;}}void main() {counterStream().listen((value) {print('Counter: $value');});}
In summary, futures represent a single asynchronous operation that will complete with a value or an error, while streams represent a sequence of asynchronous events over time. Both futures and streams are essential for handling asynchronous operations in Dart and are used extensively in Dart libraries and frameworks like Flutter for building responsive and reactive applications.