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
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.
1 2 |
CancelToken cancelToken = CancelToken(); cancelToken?.cancel("Reason for cancelling"); |
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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
@RestApi(baseUrl: "Your app base URL ") abstract class ApiClient { factory ApiClient( {String? baseUrl, CancelToken? cancelToken}) { Dio dio = Dio(); dio.options = BaseOptions( receiveTimeout: Duration(milliseconds: 90000), connectTimeout: Duration(milliseconds: 90000), baseUrl: ApiConstant.baseUrl); dio.options.headers["Content-Type"] = "application/json"; RequestOptions? reqOptions; dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) { reqOptions = options; if (cancelToken != null) { reqOptions?.cancelToken = cancelToken; } return handler.next(options); }, onResponse: (response, handler) async { log("Response::: $response"); return handler.next(response); }, onError: (DioError e, handler) { if (DioErrorType.cancel == e.type) { print("REquest Cancel----- Inside IF"); } else { DioExceptions.fromDioError(e).retryApiFromClient(e, reqOptions, dio, handler); } return handler.next(e); })); return _ApiClient(dio, baseUrl: baseUrl); } |
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.
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
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.