Sub topic 3
Setting deadlines with timeout
This chapter assumes you know Dart functions, generics such as List<int>, async and await, and how to run a file with dart run.
Setting deadlines with timeout
Future.timeout returns a new Future. If the original Future does not complete within the given duration, the new Future fails with a TimeoutException.
import 'dart:async';
Future<String> slowOperation() =>
Future.delayed(const Duration(seconds: 5), () => 'finished');
Future<void> main() async {
try {
final result = await slowOperation().timeout(const Duration(seconds: 1));
print(result);
} on TimeoutException {
print('timed out');
}
}The timeout stops the caller from waiting. It does not cancel the underlying operation, which keeps running until it finishes.
Common mistakes and how to avoid them
Three mistakes appear often.
- Missing
await. Withoutawait, the code continues before the result arrives. The variable holds a Future, not the value. - Unawaited Futures. A Future that nobody awaits can fail, and no code catches the error.
- Plain
returninsidetry. A statement likereturn fetchData();passes the Future out of the function, so thecatchblock never sees its error. Writereturn await fetchData();instead.
Bridging callbacks to Futures with Completer
A Completer creates a Future that your code completes by hand. Use it when an older API reports results through callbacks.
import 'dart:async';
Future<int> countdown(int from) {
final completer = Completer<int>();
var n = from;
Timer.periodic(const Duration(milliseconds: 100), (timer) {
n--;
if (n == 0) {
timer.cancel();
completer.complete(from);
}
});
return completer.future;
}
Future<void> main() async {
final started = await countdown(3);
print('counted down from $started');
}From Futures to Streams: await for
A Stream delivers many values over time. await for handles each value as it arrives.
Stream<int> ticks(int count) async* {
for (var i = 1; i <= count; i++) {
await Future<void>.delayed(const Duration(milliseconds: 200));
yield i;
}
}
Future<void> main() async {
await for (final t in ticks(3)) {
print('tick $t');
}
}Offloading heavy work with Isolate.run
Dart runs all Future callbacks on one event loop. A long calculation blocks that loop, so other work waits. Isolate.run runs a function in a separate isolate and returns its result as a Future.
import 'dart:isolate';
int sumTo(int n) {
var total = 0;
for (var i = 1; i <= n; i++) {
total += i;
}
return total;
}
Future<void> main() async {
final result = await Isolate.run(() => sumTo(100000000));
print(result);
}Exercise
A call to slowOperation().timeout(const Duration(seconds: 1)) throws a TimeoutException. Does slowOperation stop running? Explain why.
Show answer
No. Future.timeout only stops the caller from waiting. The underlying operation keeps running until it completes, and its result is discarded.