What is a Future?
A Future represents a potential value or error that will be available at some time in the future. It's a core part of Dart's asynchronous programming model. Instead of blocking the program while waiting for an operation (like a network request, file I/O, or timer), a Future allows the program to continue executing other code and be notified when the result is ready.
Futures can be in one of two states: uncompleted or completed. When completed, they either complete with a value or with an error.
Creating a Future
There are several ways to create a Future in Dart:
Future.value– creates a Future that completes immediately with a given value.
Future.error– creates a Future that completes immediately with an error.
Future.delayed– creates a Future that completes after a specified duration.
Future.sync– creates a Future that runs a function synchronously and then completes with its result (or error).
- Using
asyncfunctions – anyasyncfunction automatically returns a Future.
- Using
Using then() to Handle Completion
The most basic way to handle a Future's result is with the .then() method. It takes a callback that will be called with the value when the Future completes successfully.
Handling Errors with catchError
You can handle errors by chaining a .catchError() callback. It works similarly to a catch block.
Using whenComplete for Cleanup
The .whenComplete() callback runs regardless of whether the Future completes with a value or an error. It's useful for cleanup actions (like closing a file or hiding a loading spinner).
Chaining Futures
You can chain multiple asynchronous operations by returning a Future from a .then() callback. This avoids nested callbacks (callback hell).
Working with Multiple Futures
Dart provides several static methods for working with multiple Futures:
Future.wait– waits for all Futures to complete, then gives a list of results. If any Future completes with an error,waitcompletes with that error.
Future.any– completes with the result of the first Future that completes (success or error).
Future.doWhile– performs an action repeatedly until it returnsfalse.
Async/Await: A Cleaner Alternative
While you can use .then() and .catchError(), the async/await syntax is often more readable. An async function returns a Future, and await pauses the function until the Future completes. Error handling is done with try/catch.
Key Takeaways
- A Future represents a value or error that will be available later.
- Create Futures using
Future.value,Future.error,Future.delayed, or by writingasyncfunctions.
- Create Futures using
- Use
.then()to handle successful completion,.catchError()for errors, and.whenComplete()for cleanup.
- Use
- Chain Futures by returning a new Future from
.then().
- Chain Futures by returning a new Future from
- Use
Future.waitto run multiple Futures concurrently and wait for all to complete.
- Use
- Prefer
async/awaitfor cleaner, more readable asynchronous code.
- Prefer