Future
- Dart course
- Beginner
- Lesson 106/116
- 5 min
Learn asynchronous operations with Future.
Future
A Future represents the result of an operation that has not finished yet. An asynchronous operation starts and the result comes later. For example a network call, file read or timer. Future<int> is a Future that will carry an int value.
A Future is in one of three states: pending, completed (with a value) or errored. Future.value(42) creates a Future that completes immediately with 42. Future.delayed(Duration(seconds: 1), () => 42) completes after one second. To wait for the result you use then or await; we will see this in the next lesson.
Creating a Future
The simplest Future is created with Future.value(...). It completes immediately carrying the value you give. final f = Future.value("ready");. This is useful to mimic the result of an asynchronous operation. Future.error(Exception("error")) creates a Future that completes with an error.
For a delayed Future use Future.delayed. Future.delayed(Duration(milliseconds: 100), () => 42) completes with 42 after 100 ms. The Duration class carries a time interval; units like seconds, milliseconds, minutes. We will see what to do when the result arrives in the next step. We are not fetching its value yet; we are holding the Future object.
Practice Your turn: Future and then
Create a Future with Future.value(42). Print its value with .then((v) => print(v)). The value appears on the screen when the Future completes.
Starter code
void main() {
// Create a value Future
// print its value when it completes
}Sample solution
void main() {
Future.value(42).then((v) => print(v));
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Future<T> represent?
Future<int> f = Future.value(42);- An error object
- A present T value
- A T value that will arrive Correct answer
- A loop
Explanation: Future<T> carries a T value that arrives later.
2 Future.value
final f = ____.value(42);
final f = Future.value(42);
Explanation: Future.value creates a Future that completes now.
3 Match Future
| Term | Meaning |
|---|---|
Future<T> |
a T value later |
Future.value |
completes immediately |
Future.delayed |
completes after a delay |
pending |
not yet finished |