In Flutter/Dart, a Future represents a potential value or error that will be available at some point in the future, while FutureBuilder is a Flutter widget designed to easily build UI based on the current state of a Future.
Understanding the difference is key to handling asynchronous operations and updating your user interface accordingly.
What is a Future?
A Future
is an object representing a delayed computation. It's a placeholder for a result that isn't available immediately because the operation takes time (e.g., fetching data over the network, reading a file, performing a complex calculation).
Think of a Future
like ordering food at a restaurant: you place the order (start the asynchronous operation) and get a ticket (the Future
object). You don't have the food immediately, but you have a promise that it will arrive eventually.
A Future
can be in one of three states:
- Incomplete: The operation is still running.
- Completed with a value: The operation finished successfully and produced a result.
- Completed with an error: The operation failed.
You interact with a Future
by attaching callbacks using methods like .then()
, .catchError()
, or .whenComplete()
to handle the result or error when it becomes available.
Example:
Future<String> fetchData() async {
// Simulate a network request
await Future.delayed(Duration(seconds: 2));
return "Data fetched successfully!";
}
void processData() {
fetchData().then((data) {
print(data); // This runs after 2 seconds
}).catchError((error) {
print("Error fetching data: $error");
});
}
What is FutureBuilder?
FutureBuilder
is a stateful Flutter widget specifically designed to rebuild its UI based on the latest state of a Future
. It simplifies the process of showing different widgets while waiting for a Future
to complete, when it completes successfully, or if it completes with an error.
As the reference states, FutureBuilder works by taking a Future and a builder function; then it waits for the Future to complete. Once Future completes or encounters an error message, FutureBuilder calls the builder's function. The builder function then builds the widget per the current state of the Future computation.
The builder
function provided to FutureBuilder
receives an AsyncSnapshot
, which contains information about the Future
's current state (is it waiting? does it have data? does it have an error?). Based on this AsyncSnapshot
, you can return the appropriate widget (e.g., a loading spinner, the loaded data, or an error message).
Example:
FutureBuilder<String>(
future: fetchData(), // The Future to track
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(); // Show loading spinner
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}'); // Show error message
} else {
return Text('Data: ${snapshot.data}'); // Show the data
}
},
)
Key Differences: Future vs. FutureBuilder
Feature | Future | FutureBuilder |
---|---|---|
Type | An object representing an async operation | A Flutter Widget |
Purpose | To perform an asynchronous task | To build UI that depends on the state of a Future |
Handling | Handled in code using .then() , .catchError() , etc. |
Handled by the widget; UI updates automatically |
Rebuilding | Does not inherently trigger UI rebuilds | Automatically rebuilds its child widget when the Future 's state changes |
Usage | Used in application logic, data fetching, etc. | Used in the widget tree to display async data/states |
In essence, a Future
is the asynchronous task itself, while FutureBuilder
is the tool in the UI layer that helps you easily visualize the progress and result of that Future
. You need a Future
before you can use a FutureBuilder
.