Sobes.tech
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:

  1. Using a cancellation flag — check a special flag inside an asynchronous function and interrupt execution.

  2. Using CancelableOperation from the async package — wraps a Future and allows calling the cancel() method.

  3. Using Stream instead of Future — streams can be closed, thus interrupting processing.

  4. 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., CancelToken in 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');
  }
}