Back to results for “Async await”
Flutter › Dart Asynchronous Programming (Future & async/await)

How can you properly cancel an in progress asynchronous operation in Dart, such as a network request, when it is no longer actually needed, for example because the user has already navigated away from that specific screen?

Advanced

Answer

Dart's core Future type does not provide a universal built in cancellation mechanism on its own, so cancelling an in progress asynchronous operation typically requires either using a package specifically designed to support cancellation, such as one built around the CancelToken pattern commonly used with the Dio networking package, or manually tracking a boolean flag or checking whether a StatefulWidget is still actually mounted before applying the eventual result of a Future, which correctly prevents unnecessary work from continuing, or a completed result from being incorrectly applied, to a screen the user has already navigated away from.
final cancelToken = CancelToken();
dio.get(url, cancelToken: cancelToken);

// When no longer needed
cancelToken.cancel('Screen was disposed');
Real-world example A search screen cancels its previous in progress network request using a Dio CancelToken the moment a user types a new search query, avoiding a wasted, unnecessary network request for search results the user no longer actually cares about.

Common follow-ups: What happens to a Future's eventual result if the underlying operation cannot actually be cancelled but the requesting widget has already been disposed?;How do you properly check whether a StatefulWidget is still mounted before safely calling setState after an await?