How to Cancel HTTP Requests with CancelToken and Riverpod

Did you know?

CancelToken lets you cancel HTTP requests on demand.

It's great for optimizing network usage, improving UX, and handling timeouts.

Use it to stop unnecessary data fetches when users navigate away or to implement "cancel" buttons in your Flutter apps.

How to use CancelToken with Dio and Riverpod
How to use CancelToken with Dio and Riverpod

Example code

import 'package:dio/dio.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; @riverpod Future<TMDBMoviesResponse> fetchMovies( FetchMoviesRef ref, { required int page, }) async { // 1. Create the CancelToken final cancelToken = CancelToken(); // 2. Cancel it on dispose ref.onDispose(() => cancelToken.cancel()); // 3. Pass it along when making a request return nowPlayingMovies( page: page, cancelToken: cancelToken, ); } Future<TMDBMoviesResponse> nowPlayingMovies( {required int page, CancelToken? cancelToken}) async { final uri = Uri(/* uri params */); final response = await dio.getUri(uri, cancelToken: cancelToken); return TMDBMoviesResponse.fromJson(response.data); }

CancelToken works great in combination with Riverpod.

Here's a more in-depth example showing how to implement a caching-with-timeout strategy:

Happy coding!

Want More?

Invest in yourself with my high-quality Flutter courses.

Flutter In Production

Flutter In Production

Learn about flavors, environments, error monitoring, analytics, release management, CI/CD, and finally ship your Flutter apps to the stores. 🚀

Flutter Foundations Course

Flutter Foundations Course

Learn about State Management, App Architecture, Navigation, Testing, and much more by building a Flutter eCommerce app on iOS, Android, and web.

Flutter & Firebase Masterclass

Flutter & Firebase Masterclass

Learn about Firebase Auth, Cloud Firestore, Cloud Functions, Stripe payments, and much more by building a full-stack eCommerce app with Flutter & Firebase.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Last updated to Dart 2.15.

Flutter Animations Masterclass

Flutter Animations Masterclass

Master Flutter animations and build a completely custom habit tracking application.