Sub topic 9
Setting deadlines with `Future.timeout`
Assume you know basic Dart functions, types, callbacks, and how to run a program with dart run. You should also understand that a Future<T> represents a result that may become available later.
A timeout gives asynchronous work a deadline. If the Future does not complete before that deadline, the timed operation completes with a timeout error or with a fallback value that you provide.
Why use a timeout?
Network requests, database queries, and other external operations can take an unpredictable amount of time. Without a deadline, your code might keep showing a loading indicator forever.
The timeout method returns another Future. It waits for the original future only for the specified duration.
import 'dart:async';
Future<String> loadProfile() {
return Future.delayed(
const Duration(seconds: 5),
() => 'Ada Lovelace',
);
}
Future<void> main() async {
try {
final name = await loadProfile().timeout(
const Duration(seconds: 1),
);
print(name);
} on TimeoutException {
print('The profile took too long to load.');
}
}This program waits for at most one second. Since loadProfile takes five seconds, the await throws a TimeoutException, and the on clause handles it.
The timeout duration is a Duration. Choose it according to the operation. A local cache may need only a short deadline, while a slow network request may need longer.
Providing a fallback
You can pass an onTimeout callback to return a replacement value:
Future<String> loadMessage() {
return Future.delayed(
const Duration(seconds: 3),
() => 'Message from server',
);
}
Future<void> main() async {
final message = await loadMessage().timeout(
const Duration(seconds: 1),
onTimeout: () => 'Using cached message',
);
print(message);
}Here, the returned future completes with Using cached message instead of throwing. The callback can also return a future if creating the fallback is asynchronous.
| Approach | Result after the deadline | Best when |
|---|---|---|
| No `onTimeout` | Throws `TimeoutException` | The operation must succeed |
| `onTimeout` returns a value | Completes with a fallback | Stale or cached data is acceptable |
| `onTimeout` throws | Completes with that error | You want a domain-specific failure |
A timeout does not cancel the original work
timeout changes what the returned future does. It does not automatically stop the original operation.
For example, loadProfile from the first example may still finish after five seconds. Its result is ignored by the timed future because that future has already completed with a timeout error.
If the underlying API supports cancellation, use that API when a timeout occurs. For example, an HTTP client may provide a request object that can be cancelled. A plain Future has no general cancellation method.
Combining timeout with error handling
A timeout is one possible failure. The original operation may also fail for another reason, such as an unavailable server.
Handle both cases explicitly:
import 'dart:async';
Future<int> fetchCount() async {
await Future<void>.delayed(const Duration(milliseconds: 300));
throw StateError('Server rejected the request');
}
Future<void> main() async {
try {
final count = await fetchCount().timeout(
const Duration(seconds: 1),
);
print('Count: $count');
} on TimeoutException {
print('The request timed out.');
} on StateError catch (error) {
print('The request failed: $error');
} finally {
print('Request finished.');
}
}The finally block runs whether the future succeeds, fails, or times out. In a Flutter widget, use this pattern to stop a loading state in every outcome.
Exercise
What does await operation.timeout(const Duration(seconds: 2)) do if operation completes after three seconds and no onTimeout callback is supplied?
Show answer
The timed future completes with a TimeoutException after two seconds. The original operation may still continue in the background.