Request Cancellation In Flutter

Updated 31 October 2023


In this blog, we will learn how we can implement Request Cancellation In Flutter in Rest API calls.
While developing flutter applications, we can cancel the existing request using the Cancel Token class.
When we are calling the same API request again and again that might increase the load on the server and on the application too or we may encounter inaccuracy in data. So it is a better approach to cancel the existing running request and create a new request.

Before moving further, you can also check our Flutter app development company page.

Let’s demonstrate the Request canceling flow using the Cancel Token Class

1. Initialization

Firstly, we will initialize the CancelToken class and create an object for sending it further to the API client class where all magic will happen.

While creating the instance of CancelToken, we can pass the reason also as an argument due to which we are canceling the API call or network request.

2. Implementation

Now, we can use the cancel token in the API client in which we have declared all the network calls. In our demo, we have used retrofit for the network calls and we have used the Cancel token in the same.

As we know, retrofit internally uses Dio for all network calls. We can add the cancel token while adding interceptors in the API client-creating process, if the cancel token is not null then we will add it to request options so running network call requests will be canceled before creating the new request.

3. Conclusion

In this blog, you have learned how we can use the CancelToken class for Request Cancellation In Flutter.

You can also check the Flutter official site for more information regarding the same

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home