Junior — Middle
How can you cancel a task associated with a Future?
sobes.tech AI
Answer from AI
In Dart (and Flutter), a Future object itself does not support direct cancellation of a task. However, there are several approaches to cancel:
-
Using a cancellation flag — check a special flag inside an asynchronous function and interrupt execution.
-
Using
CancelableOperationfrom theasyncpackage — wraps a Future and allows calling thecancel()method. -
Using
Streaminstead of Future — streams can be closed, thus interrupting processing. -
Cancellation at the source of the task — for example, if a Future is related to an HTTP request, you can cancel the request via a controller (e.g.,
CancelTokenin Dio).
Example with CancelableOperation:
import 'package:async/async.dart';
void main() async {
var cancelable = CancelableOperation.fromFuture(
Future.delayed(Duration(seconds: 5), () => 'Done'),
);
// Cancel after 2 seconds
Future.delayed(Duration(seconds: 2), () {
cancelable.cancel();
print('Cancelled');
});
try {
var result = await cancelable.value;
print(result);
} catch (e) {
print('Operation was cancelled');
}
}