CacheInterceptor class

Interceptor that provides response caching with configurable strategies.

Supports multiple caching strategies:

The TTL is enforced here, not by the CacheStorage: a backend only stores and returns. See CacheStorage.get.

Whenever a cached body is handed back, Response.extra carries fromCacheKey, plus fromCacheStaleKey when that body had expired — read them through response.isFromCache / response.isStale.

Example:

final cacheInterceptor = CacheInterceptor(
  config: CacheConfig(
    strategy: CacheStrategy.networkFirst,
    defaultTtl: Duration(minutes: 5),
  ),
);
dio.interceptors.add(cacheInterceptor);
Inheritance

Constructors

CacheInterceptor({required CacheConfig config})
Creates a CacheInterceptor with the given config.

Properties

config → CacheConfig
The cache configuration.
final
deduplicator → RequestDeduplicator
Returns the request deduplicator (for testing).
no setter
hashCode → int
The hash code for this object.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

clearCache() → Future<int>
Clears all cached entries.
evictExpired() → Future<int>
Removes every entry that is past its TTL, and returns how many went.
getCacheKeys() → Future<List<String>>
Returns all current cache keys, expired entries included.
hasCache(String key) → Future<bool>
Returns true if a cache entry exists for the given key.
invalidate(String key) → Future<bool>
Invalidates a specific cache entry by its exact key.
invalidateByPrefix(String prefix) → Future<int>
Invalidates all cache entries whose keys start with the given prefix.
invalidatePath(String pathPattern) → Future<int>
Invalidates all cache entries for a specific path pattern.
invalidateUrl(String url, {String method = 'GET'}) → Future<bool>
Invalidates all cache entries for a specific URL and method.
invalidateWhere(bool predicate(String key)) → Future<int>
Invalidates all cache entries matching a predicate.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
onError(DioException err, ErrorInterceptorHandler handler) → void
Called when an exception was occurred during the request.
override
onRequest(RequestOptions options, RequestInterceptorHandler handler) → void
Called when the request is about to be sent.
override
onResponse(Response response, ResponseInterceptorHandler handler) → void
Called when the response is about to be resolved.
override
setDio(Dio dio) → void
Sets the Dio instance for deduplication. Must be called after adding this interceptor to Dio.
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited