dio_http_cache 0.2.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 94

dio-http-cache #

中文介绍

Dio-http-cache is a cache library for Dio ( http client for flutter ), like Rxcache in Android.

Dio-http-cache uses sqflite as disk cache, and LRU strategy as memory cache.

Inspired by flutter_cache_manager.

Add Dependency #

dio_http_cache: ^0.2.0

If you are using dio 2.x:

dio_http_cache: ^0.1.4
# or : (to get the latest update in 2.x)
dio-http-cache:
	git:
		url: git@github.com:hurshi/dio-http-cache.git
		ref: v2.x

QuickStart #

  1. Add a dio-http-cache interceptor in Dio :

    dio.interceptors.add(DioCacheManager(CacheConfig(baseUrl: "http://www.google.com")).interceptor);
    
  2. Set maxAge for a request :

    Dio().get(
      "http://www.google.com",
      options: buildCacheOptions(Duration(days: 7)),
    );
    

The advanced #

  1. Custom your config by buildCacheOptions :

    1. primaryKey: By default, host + path is used as the primaryKey, and you can also customize it.

    2. subKey: By default, query ( data or queryParameters) is used as subKey, and you can specify the subKey when it's necessary, for example:

      buildCacheOptions(Duration(days: 7), subKey: "page=1")
      
    3. maxAge: the only required param, set the cache time;

    4. maxStale: set stale time. When an error (like 500,404) occurs before maxStale, try to return cache .

      buildCacheOptions(Duration(days: 7), maxStale: Duration(days: 10))
      
    5. forceRefresh: false default.

      buildCacheOptions(Duration(days: 7), forceRefresh: true)
      
      1. Get data from network first.
      2. If getting data from network succeeds, store or refresh cache.
      3. If getting data from network fails or no network avaliable, try get data from cache instead of an error.
  2. Use "CacheConfig" to config default params

    1. encrypt / decrypt: These two must be used together to encrypt the disk cache data, otherwise use base64 as default.
    2. DefaultMaxAge: use Duration(day:7) as default.
    3. DefaultaMaxStale: similar with DefaultMaxAge.
    4. DatabaseName: database name.
    5. SkipMemoryCache: false defalut.
    6. SkipDiskCache: false default.
    7. MaxMemoryCacheCount: 100 defalut.
  3. How to clear expired cache

    • Just ignore it, that is automatic.

    • But if you insist : DioCacheManager.clearExpired();

  4. How to delete caches

    1. No matter what subKey is, delete local cache if primary matched.

      // Automatically parses primarykey from path
      _dioCacheManager.deleteByPrimaryKey(path); 
      
    2. Delete local cache when both primaryKey and subKey matched.

      // delete local cache when both primaryKey and subKey matched.
      _dioCacheManager.deleteByPrimaryKeyAndSubKey(path); 
      

      INPORTANT: If you have additional parameters when requesting the http interface, you must take them with it, for example:

      _dio.get(_url, queryParameters: {'k': keyword}, 
        options: buildCacheOptions(Duration(hours: 1)))
      //delete the cache:
      _dioCacheManager.deleteByPrimaryKeyAndSubKey(_url, queryParameters:{'k': keyword}); 
      
      _dio.post(_url, data: {'k': keyword}, 
        options: buildCacheOptions(Duration(hours: 1)))
      //delete the cache:
      _dioCacheManager.deleteByPrimaryKeyAndSubKey(_url, data:{'k': keyword}); 
      
    3. Delete local cache by primaryKey and optional subKey if you know your primarykey and subkey exactly.

      // delete local cache by primaryKey and optional subKey
      _dioCacheManager.delete(primaryKey,{subKey});
      
  5. How to clear All caches (expired or not)

    _dioCacheManager.clearAll();
    

Example for maxAge and maxStale #

_dio.post(
	"https://www.exmaple.com",
	data: {'k': "keyword"},
	options:buildCacheOptions(
  		Duration(days: 3), 
  		maxStale: Duration(days: 7), 
	)
)
  1. 0 ~ 3 days : Return data from cache directly (irrelevant with network).
  2. 3 ~ 7 days:
    1. Get data from network first.
    2. If getting data from network succeeds, refresh cache.
    3. If getting data from network fails or no network avaliable, try get data from cache instead of an error.
  3. 7 ~ ∞ days: It won't use cache anymore, and the cache will be deleted at the right time.

License #

Copyright 2019 Hurshi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

[0.2.0] - 2019-09-20

  • support for dio 3.0

[0.1.4] - 2019-09-17

  • Fix bug for remove memory cache by primary key

[0.1.3] - 2019-08-21

  • Change primaryKey to "host + path", and automatically use queryParams as the subKey.
  • Support for delete caches by primaryKey. (Parsing primaryKey from path).
  • Support for delete one cache by primaryKey and subKey. (Parsing primaryKey and subKey from path).

[0.1.2] - 2019-08-06

  • Return Future
  • Returns statusCode=200 if data was retrieved from the cache successfully.
  • Support for forced data refresh from the network.

[0.1.1] - 2019-07-24

  • Support delete all cache.

[0.1.0] - 2019-07-14

  • This is a pre-release version.
  • support disk cache.
  • support memory cache.
  • support key and subKey.
  • support maxAge and maxStale.

example/README.md

Access the details on Github

Use this package as a library

1. Depend on it

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


dependencies:
  dio_http_cache: ^0.2.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support 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_http_cache/dio_http_cache.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
89
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
94
Learn more about scoring.

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

  • Dart: 2.5.1
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
crypto ^2.1.1+1 2.1.3
dio ^3.0.1 3.0.3
flutter 0.0.0
json_annotation ^3.0.0 3.0.0
json_serializable ^3.0.0 3.2.3
path ^1.6.2 1.6.4
quiver ^2.0.3 2.0.5
sqflite ^1.1.6+3 1.1.7+1
Transitive dependencies
analyzer 0.38.5 0.39.0
args 1.5.2
async 2.4.0
build 1.2.0
build_config 0.4.1+1
charcode 1.1.2
checked_yaml 1.0.2
collection 1.14.11 1.14.12
convert 2.1.1
csslib 0.16.1
dart_style 1.3.2
front_end 0.1.27 0.1.28
glob 1.2.0
html 0.14.0+3
http_parser 3.1.3
js 0.6.1+1
kernel 0.3.27 0.3.28
logging 0.11.3+2
matcher 0.12.6
meta 1.1.7
node_interop 1.0.3
node_io 1.0.1+2
package_config 1.1.0
pedantic 1.8.0+1
pub_semver 1.4.2
pubspec_parse 0.1.5
sky_engine 0.0.99
source_gen 0.9.4+5
source_span 1.5.5
stack_trace 1.9.3
string_scanner 1.0.5
synchronized 2.1.0+1
term_glyph 1.1.0
typed_data 1.1.6
vector_math 2.0.8
watcher 0.9.7+12
yaml 2.2.0
Dev dependencies
build_runner ^1.6.6
flutter_test