Caching is a crucial process for storing API responses on a user's device to reduce network requests and improve performance in Flutter apps. This example demonstrates how to implement caching for API requests using the Dio HTTP client and the Dio Cache Interceptor.
- Dio: A powerful HTTP client for Flutter.
- Dio Cache Interceptor: An interceptor for Dio that allows efficient API response caching.
- Hive: A fast and lightweight key-value database in Dart used as the cache store.
In your `pubspec.yaml` file, add the required packages:
dependencies:
dio: ^4.0.6
dio_cache_interceptor: ^3.3.0
dio_cache_interceptor_hive_store: ^3.2.0
hive: ^2.0.5
Get the temporary directory on the device where cached data will be stored. It's recommended to use the temporary directory provided by Flutter:
var cacheDir = await getTemporaryDirectory();
Create a cacheStore object, specifying the cache directory path and a unique hiveBoxName for your app:
var cacheStore = HiveCacheStore(
cacheDir.path,
hiveBoxName: "your_app_name",
);
Customize cache options to control caching behavior, such as cache policy, priority, maxStale duration, key building, and more:
var customCacheOptions = CacheOptions(
store: cacheStore,
policy: CachePolicy.forceCache,
priority: CachePriority.high,
maxStale: const Duration(minutes: 5),
hitCacheOnErrorExcept: [401, 404],
keyBuilder: (request) {
return request.uri.toString();
},
allowPostMethod: false,
);
Create a Dio instance and add the cache interceptor with your custom cache options:
var customDio = Dio()
..interceptors.add(DioCacheInterceptor(options: customCacheOptions));
Follow these best practices when using Dio for network requests:
- Use Dio's try-catch mechanism to handle network errors gracefully.
- Implement loading indicators to provide feedback during network requests.
- Handle timeouts and connectivity issues.
- Display appropriate error messages to the user.
Now, all your GET requests made using the customDio object will be cached in the user's device storage temporary directory while following best practices for network calling and error handling.
Feel free to explore and customize this example for your Flutter app's caching needs.