A plugin for dio that caches responses for better optimization and offline data access.


import 'package:dio_cache/dio_cache.dart';

Basic configuration

final dio = Dio()

Global caching options

final dio = Dio()
    options: const CacheOptions(
      store: MemoryCacheStore(), // The store used for response cache
      forceUpdate: false, // Forces to update even if cache isn't expired
      forceCache: false, // Forces to use cache, even if expired
      priority: CachePriority.normal, // Setting a priority to clean only several requests
      returnCacheOnError: true, // Returns a cached response on error if available
      isCached: true, // Bypass caching if [false]
      expiry: const Duration(minutes: 1), // The cache expiry, after which a new request is triggered instead of getting the cached response
      keyBuilder: (request) => "${request.method}_${CacheInterceptor.uuid.v5(Uuid.NAMESPACE_URL, request.uri.toString())}" // Builds the unqie key used for indexing a request in cache (this may be useful if arguments aren't passed in query but in body)

Sending a request with options

final forcedResponse = await dio.get("http://www.flutter.dev", options: Options(
    extra: CacheOptions(
      forceUpdate: true

Cleaning cached values from global store


Getting more info about caching status

final response = await dio.get("http://www.flutter.dev");
final cachedResult = CacheResult.fromExtra(response);
if(cachedResult.isFromCache) {
  print("expiry: ${cachedResult.cache.expiry}, downloadedAt: ${cachedResult.cache.downloadedAt}");

Invalidating a cached value from global store

final cachedResult = CacheResult.fromExtra(response);

Logging caching operations

final dio = Dio()
  ..interceptors.add(CacheInterceptor(logger: Logger("Cache")));

Availables stores

MemoryCacheStoreStores all cached responses in a map in memory
FileCacheStoreStores each request in a dedicated file
BackupCacheStoreReads values primarly from memory and backup values to specified store (ex: a FileCacheStore)
FilteredCacheStoreIgnoring responses for save

Features and bugs

Please file issues.