Dart Futures
Dart Futures
A Future is a value that is not ready yet, but will be ready later.
You can think of it like a receipt from a restaurant: you do not have your food yet, but you will get it when it is ready.
A future is always in one of these states:
- Uncompleted: the task is still running
- Completed with a value: the task worked, and the result is ready
- Completed with an error: the task failed
The type of a future says what kind of value it will give you.
For example, Future<String> will give you a String, and Future<int> will give you an int.
Create a Future
Future.delayed() creates a future that completes after a waiting time.
The value that the function returns becomes the value of the future.
If you print the future itself, you do not see the value, only the type of the future:
Example
void main() {
Future<String> order = Future.delayed(Duration(seconds: 1), () {
return 'Pizza';
});
print(order);
}
Try it Yourself »
Result:
Instance of 'Future<String>'
Get the Value With then()
The then() method runs a function when the future completes with a value.
The value is passed to the function as a parameter:
Example
void main() {
Future<String> order = Future.delayed(Duration(seconds: 1), () {
return 'Pizza';
});
order.then((food) {
print('Your $food is ready');
});
print('Waiting for the order...');
}
Try it Yourself »
Result:
Waiting for the order...
Your Pizza is ready
Notice that Waiting for the order... is printed first, because the code after then() does not wait.
You can chain then() calls.
The value that one then() returns is passed to the next one:
Example
void main() {
Future.delayed(Duration(seconds: 1), () => 5)
.then((price) => price * 2)
.then((total) {
print('Total: $total dollars');
});
}
Try it Yourself »
Result:
Total: 10 dollars
Handle Errors With catchError()
If the task throws an exception, the future completes with an error.
The catchError() method runs a function when this happens:
Example
void main() {
Future<String> order = Future.delayed(Duration(seconds: 1), () {
throw Exception('The kitchen is closed');
});
order.then((food) {
print('Your $food is ready');
}).catchError((error) {
print('Something went wrong: $error');
});
}
Try it Yourself »
Result:
Something went wrong: Exception: The kitchen is closed
The function inside then() did not run, because the future did not get a value.
Note: If a future fails and nothing handles the error, the program stops with an error message.
A Future That Is Already Done
Future.value() creates a future that already has a value.
This is useful when a function must return a future, but the value is already known:
Example
void main() {
Future<int> score = Future.value(100);
score.then((value) {
print('Score: $value');
});
print('This line is printed first');
}
Try it Yourself »
Result:
This line is printed first
Score: 100
Even when the value is ready, the function in then() still runs after the normal code.
Wait for Many Futures
Future.wait() takes a list of futures and returns one new future.
The new future completes when all the futures are done, and its value is a list with all the results, in the same order as the input list:
Example
void main() {
Future<String> drink = Future.delayed(Duration(seconds: 2), () => 'Coffee');
Future<String> food = Future.delayed(Duration(seconds: 1), () => 'Sandwich');
Future.wait([drink, food]).then((results) {
print(results);
print('Breakfast is ready');
});
}
Try it Yourself »
Result:
[Coffee, Sandwich]
Breakfast is ready
Both futures run at the same time, so this takes about 2 seconds, not 3.
In the next chapter, you will learn async and await, which make code with futures easier to read.