dio_cache 0.4.0-beta

dio_cache #

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

Usage #

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.

1.0.0 #

  • Initial version, created by Stagehand


import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio_cache/dio_cache.dart';
import 'package:logging/logging.dart';

main() async {
  // Displaying logs
  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((record) {
    print('${record.level.name}: ${record.time}: ${record.message}');

  // Add the interceptor with optional options
  final cacheInterceptor = CacheInterceptor(
    logger: Logger("Cache"),
    options: CacheOptions(
      expiry: const Duration(minutes: 30),
      store: BackupCacheStore(backupStore: FileCacheStore(Directory(".cache"))),
  final dio = Dio()..interceptors.add(cacheInterceptor);

  // The first request will get data and add it to cache
  final distantResponse = await dio.get("http://www.flutter.dev");
      "Distant -> statusCode: ${distantResponse.statusCode}, data : ${distantResponse.data.substring(0, 20)}...");

  await Future.delayed(const Duration(seconds: 5));

  // The second request will use the cached value
  final cachedResponse = await dio.get("http://www.flutter.dev");
      "Cached -> statusCode: ${cachedResponse.statusCode}, data : ${distantResponse.data.substring(0, 20)}...");

  // To get more info about the cache
  final cachedExtra = CacheResult.fromExtra(cachedResponse);
  if (cachedExtra.isFromCache) {
        "isFromCache: ${cachedExtra.isFromCache}, expiry: ${cachedExtra.cache.expiry}, downloadedAt: ${cachedExtra.cache.downloadedAt}");

  // The new request will get data and add it to cache
  final forcedResponse = await dio.get("http://www.flutter.dev",
      options: Options(
        extra: CacheOptions(forceUpdate: true).toExtra(),
      "Forced -> statusCode: ${forcedResponse.statusCode}, data : ${forcedResponse.data.substring(0, 20)}...");

  // To get more info about the cache
  final forcedCachedExtra = CacheResult.fromExtra(forcedResponse);
  print("isFromCache: ${forcedCachedExtra.isFromCache}");

  // To invalidate a cached request
  final key = await cacheInterceptor.options.store.invalidate(cachedExtra.cache.key);

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  dio_cache: ^0.4.0-beta

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:dio_cache/dio_cache.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Jul 15, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.4.0
  • pana: 0.12.19


Detected platforms: Flutter, other

Primary library: package:dio_cache/dio_cache.dart with components: io.

Health suggestions

Fix lib/src/cache_response.dart. (-0.50 points)

Analysis of lib/src/cache_response.dart reported 1 hint:

line 67 col 9: The parameter 'key' is required.

Fix lib/src/stores/cache_store.dart. (-0.50 points)

Analysis of lib/src/stores/cache_store.dart reported 1 hint:

line 1 col 8: Unused import: 'package:dio/dio.dart'.

Fix lib/src/stores/file_cache_store.dart. (-0.50 points)

Analysis of lib/src/stores/file_cache_store.dart reported 1 hint:

line 134 col 10: The parameter 'key' is required.

Fix additional 7 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/dio_cache.dart (Run dartfmt to format lib/dio_cache.dart.)
  • lib/src/helpers/status_code.dart (Run dartfmt to format lib/src/helpers/status_code.dart.)
  • lib/src/options.dart (Run dartfmt to format lib/src/options.dart.)
  • lib/src/result.dart (Run dartfmt to format lib/src/result.dart.)
  • lib/src/stores/backup_cache_store.dart (Run dartfmt to format lib/src/stores/backup_cache_store.dart.)
  • lib/src/stores/filtered_cache_store.dart (Run dartfmt to format lib/src/stores/filtered_cache_store.dart.)
  • lib/src/stores/memory_cache_store.dart (Run dartfmt to format lib/src/stores/memory_cache_store.dart.)

Maintenance suggestions

Package is pre-release. (-5 points)

Pre-release versions should be used with caution; their API can change in breaking ways.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.0 <3.0.0
dio ^2.1.7 2.1.13
logging ^0.11.3 0.11.3+2
meta ^1.1.6 1.1.7
path ^1.6.2 1.6.2
uuid ^2.0.2 2.0.2
Transitive dependencies
charcode 1.1.2
collection 1.14.11
convert 2.1.1
cookie_jar 1.0.1
crypto 2.0.6
typed_data 1.1.6
Dev dependencies
pedantic ^1.0.0
test ^1.0.0