Back to results for “Asynchronous Programming”
Flutter › Networking with HTTP & Dio

How do you properly implement request cancellation using Dio's own CancelToken, such as cancelling a search request the moment a user genuinely types a brand new different search query?

Intermediate

Answer

Dio's CancelToken lets you properly cancel an in progress network request at any given point, and passing that specific token into your request call and later calling its own cancel method causes that particular in progress request to genuinely be aborted, which is especially useful for a scenario like a live search feature, where you genuinely want to properly cancel a previous now genuinely outdated search request the very moment a user types a brand new different query, avoiding the possibility of an older, now genuinely stale response accidentally arriving after and incorrectly overwriting a considerably newer, more genuinely relevant result.
CancelToken cancelToken = CancelToken();
dio.get(url, cancelToken: cancelToken);

// When a new search begins
cancelToken.cancel('New search initiated');
Real-world example A product search feature cancels its previous in progress search request using a Dio CancelToken every single time a user types a brand new updated query, correctly preventing an older, genuinely outdated response from accidentally arriving late and incorrectly overwriting the currently displayed more genuinely relevant results.

Common follow-ups: What genuinely specific exception type is actually thrown when a request is genuinely cancelled through a CancelToken?;How does this exact same cancellation pattern genuinely relate to properly cancelling an in progress Future more generally?