Preface
During the development process, it is very common to cancel requirements, but they can easily be ignored. However, the benefits of removing the need are also significant. For example, many requests are sent in a page. If the page is cut away and becomes invisible, you need to cancel the unfinished request task. Failure to cancel in time may result in the following negative impacts:
- Consumes additional user data traffic.
- The task callback holds global context variables, which may cause memory leaks if not released in time.
- Excessive asynchronous requests consume a lot of system resources, slow down the UI thread, and cause lags.
In Flutter, how to cancel a task that is already in progress? First you need to master some basic knowledge.
prerequisite knowledge
Future#any method
Pass in a Future task list and return the first completed asynchronous task, regardless of success or failure.
definition
usage
In the following five asynchronous tasks, although the fifth line of code is executed second, it is executed first, so the first one returns. At this point, the entire Future.any function is executed.
The result is entered as follows:
Summarize
- Future.any is actually a Completer, N Futures are superimposed together, and whoever completes it first wins.
- Future.any can be understood as a 100-meter race, in which each player is a Future. Whoever runs the fastest to the end wins.
Dio deimplementation resolution
dio version
dio: dev v5.0.3
git: 67f07b86a0976c14a6e19061563832d92ed6772b
branch: main
How to cancel
Pass in the CancelToken object in the request, and then call the token.cancel method.
final cancelToken = CancelToken();
dio.get(url, cancelToken: cancelToken).catchError((DioError err) {
if (CancelToken.isCancel(err)) {
print('Request canceled: ${err.message}');
} else{
// handle error.
}
});
// Cancel the requests with "cancelled" message.
token.cancel('cancelled');
Process analysis
Idea: Use the Future.any function to insert a cancellation task before the actual task is executed. If the actual task is not completed, there is an opportunity to cancel it.
The following code is marked in yellow and you just need to follow the steps to read it.
Summary: CancelToken is like a scumbag, while Future.any provides a fair chance to compete. As long as the girl doesn't have a boyfriend yet, the scumbag will have a chance to succeed midway.
illustrate
Canceling tasks is not limited to network requests. Any unnecessary time-consuming operations in actual business can be canceled by using Future.any with CancelToken.