Futures are a cornerstone of asynchronous programming in Dart. They represent a computation that doesn't complete immediately, allowing your code to continue executing while waiting for a result.
A Future is a placeholder for a value that will be available at some point in the future. It's commonly used for operations that might take time, such as:
You can create a Future using the Future
constructor or the Future.delayed()
method:
Future<String> fetchUserOrder() {
return Future.delayed(
Duration(seconds: 2),
() => 'Large Latte',
);
}
To work with Futures, you can use the then()
method to specify what should happen when the Future completes:
fetchUserOrder().then((order) {
print('Your order is: $order');
});
Futures can also handle errors using the catchError()
method:
fetchUserOrder()
.then((order) => print('Your order is: $order'))
.catchError((error) => print('Error: $error'));
You can chain multiple asynchronous operations using then()
:
fetchUserOrder()
.then((order) => processOrder(order))
.then((processedOrder) => deliverOrder(processedOrder))
.then((_) => print('Order completed'));
Futures are essential for writing efficient, non-blocking code in Dart. They provide a powerful way to handle asynchronous operations, making your applications more responsive and scalable.
For more advanced asynchronous programming, explore Async and Await and Dart Streams.