Future
- Dart course
- Intermediate
- Lesson 58/116
- 5 min
Learn asynchronous operations with Future.
Future
Future<T> represents an asynchronous result in Dart. When an operation is not yet complete the Future is pending; when it finishes it produces a value or throws an error.
Example: var f = Future.value(42);. This creates a Future already completed with 42. To get the result you use await: var result = await f;. await waits until the Future completes.
Futures are used for network requests, file reads, timers and similar operations. They are the way to manage long tasks without blocking the main thread.
Future.value and await
Future.value(value) creates an already completed Future. This is useful for testing and teaching; real apps use delayed operations like Future.delayed.
To get the result you use the await keyword. await works only in async marked functions. You make main async by writing void main() async.
Example: void main() async { var f = Future.value(42); var r = await f; print(r); }. Output: 42. await waits until the Future completes, then continues.
Practice Print a Future value
Write void main() async. Create a Future with Future.value(42). Wait for the result with await and assign it to a variable. Print the result with print.
Starter code
void main() async {
// produce 42 with a Future
// wait and print the result
}Sample solution
void main() async {
var f = Future.value(42);
var r = await f;
print(r);
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does a Future complete?
var f = Future.value(42);- Only on error
- When it produces a value or throws an error Correct answer
- It never completes
- Only with print
Explanation: a Future completes when it produces a value or throws an error.
2 Creating a Future
var f = ____.value(42);
var f = Future.value(42);
Explanation: Future.value creates a completed Future.
3 Match the Future parts
| Term | Meaning |
|---|---|
Future.value(42) |
Completed Future |
await f |
Waiting |
var r = await f |
Getting result |
print(r) |
Printing |