visit
You might already use CachedNetworkImage
in Flutter to avoid multiple network requests for loading images in your flutter app. This helps users by saving the mobile data and also reduces the requests made to your server for the same resource which was loaded before.
Add the required packages to the pubspec.yaml
file in your project.
hive: ^2.0.5
dio: ^4.0.6
dio_cache_interceptor: ^3.3.0
dio_cache_interceptor_hive_store: ^3.2.0
Cache Dir
The folder where you want to store the data that is being cached by the API calls. To follow the best practices we’ll use the flutter provided method to get the temporary folder of the device.var cacheDir = await getTemporaryDirectory();
build Cache-Store
Now we’ll make a cacheStore object which we need to pass to the caching interceptor to indicate the cache references.
var cacheStore = HiveCacheStore(cacheDir.path,hiveBoxName: "your_app_name",);
The above HiveCacheStore
takes two arguments, cacheDirPath(string) and the hiveBoxName(string) which can be anything you want.
CacheOptions
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,
);
CachePolicy.forceCache
— you’ll save every successful GET request.
CachePolicy.refreshForceCache
— when the origin server has no cache config, Requests regardless of cache availability, and Caches if a response has cache directives.
CachePolicy.refresh
— Requests regardless of cache availability, Cache if the response has cache directives.
CachePolicy.noCache
— Requests and skips cache save even if the response has cache directives.
high
, low
and normal
Building Dio
Finally, we build Dio object and pass in the configured cache options and the caching interceptor for caching the request made through this Dio object.
var customDio = Dio()..interceptors.add(DioCacheInterceptor(options: customCacheOptions));
And that’s it.