Junior — Middle
Is it possible to interrupt the execution of a task returned via Future, and how to do it?
sobes.tech AI
Answer from AI
In Dart (and consequently in Flutter), you cannot directly cancel a task returned by Future, as Future does not support cancellation. However, you can implement indirect cancellation using flags or controllers that are checked within the asynchronous operation.
For example, you can use a Completer and check the cancellation state:
class CancellableOperation {
bool _isCancelled = false;
Future<String> run() async {
for (int i = 0; i < 10; i++) {
if (_isCancelled) {
throw Exception('Operation cancelled');
}
await Future.delayed(Duration(seconds: 1));
}
return 'Done';
}
void cancel() {
_isCancelled = true;
}
}
void main() async {
final operation = CancellableOperation();
final future = operation.run();
// Cancel after 3 seconds
Future.delayed(Duration(seconds: 3), () {
operation.cancel();
});
try {
final result = await future;
print(result);
} catch (e) {
print(e); // Operation cancelled
}
}
For more complex cases, packages like async with CancelableOperation can be used.
Thus, direct cancellation of Future is impossible, but cancellation logic can be implemented inside the task.