-
Notifications
You must be signed in to change notification settings - Fork 81
Handling cache with client only
llfbandit edited this page Mar 29, 2025
·
8 revisions
The package won't handle any specific rule, so you will most likely have to make your own. Here are few samples to achieve correct behaviour with client only.
The samples below assume to add an interceptor before DioCacheInterceptor
to control your own rules.
Return cache if the response is aged less than 5 minutes.
dioInstance..interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, handler) {
final key = cacheOptions.defaultCacheKeyBuilder(url: options.uri, headers: request.getFlattenHeaders());
final cache = await store.get(key);
if (cache != null && DateTime.now().difference(cache.responseDate).inMinutes < 5) {
return handler.resolve(cache.toResponse(options, fromNetwork: false));
}
return handler.next(options);
},
));
Store specific URLs only.
dioInstance..interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, handler) {
if (options.uri.toString().contains('<uri_to_cache_here>')) {
final cacheOptions = CacheOptions.fromExtra(options)!;
options.extra = cacheOptions.copyWith(policy: CachePolicy.forceCache).toExtra();
return handler.next(options);
}
return handler.next(options);
},
));
// Global options
final options = const CacheOptions(
store: MemCacheStore(),
policy: CachePolicy.forceCache,
maxStale: const Duration(days: 1),
);
// ...
// Each time, this request will postpone maxStale from current date time + maxStale
// from global options
final response = await dio.get('https://www.foo.com');