diff --git a/example/.flutter-plugins-dependencies b/example/.flutter-plugins-dependencies index d9e1def..675148b 100644 --- a/example/.flutter-plugins-dependencies +++ b/example/.flutter-plugins-dependencies @@ -1 +1 @@ -{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"sqflite","path":"/Users/silvertree/.pub-cache/hosted/pub.dartlang.org/sqflite-1.3.1+1/","dependencies":[]}],"android":[{"name":"sqflite","path":"/Users/silvertree/.pub-cache/hosted/pub.dartlang.org/sqflite-1.3.1+1/","dependencies":[]}],"macos":[{"name":"sqflite","path":"/Users/silvertree/.pub-cache/hosted/pub.dartlang.org/sqflite-1.3.1+1/","dependencies":[]}],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"sqflite","dependencies":[]}],"date_created":"2020-09-24 18:44:13.977860","version":"1.20.3"} \ No newline at end of file +{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"sqflite","path":"D:\\\\Users\\\\shina\\\\Desenvolvimento\\\\flutter\\\\.pub-cache\\\\hosted\\\\pub.dartlang.org\\\\sqflite-2.0.0+1\\\\","dependencies":[]}],"android":[{"name":"sqflite","path":"D:\\\\Users\\\\shina\\\\Desenvolvimento\\\\flutter\\\\.pub-cache\\\\hosted\\\\pub.dartlang.org\\\\sqflite-2.0.0+1\\\\","dependencies":[]}],"macos":[{"name":"sqflite","path":"D:\\\\Users\\\\shina\\\\Desenvolvimento\\\\flutter\\\\.pub-cache\\\\hosted\\\\pub.dartlang.org\\\\sqflite-2.0.0+1\\\\","dependencies":[]}],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"sqflite","dependencies":[]}],"date_created":"2021-03-03 19:33:12.008560","version":"2.0.0"} \ No newline at end of file diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml index 2a56e99..61c6215 100644 --- a/example/android/app/src/main/AndroidManifest.xml +++ b/example/android/app/src/main/AndroidManifest.xml @@ -7,7 +7,6 @@ additional functionality it is fine to subclass or reimplement FlutterApplication and put your custom class here. --> + + diff --git a/example/android/app/src/main/java/com/example/example/MainActivity.java b/example/android/app/src/main/java/com/example/example/MainActivity.java index 84f8920..6d76722 100644 --- a/example/android/app/src/main/java/com/example/example/MainActivity.java +++ b/example/android/app/src/main/java/com/example/example/MainActivity.java @@ -1,13 +1,8 @@ package com.example.example; -import android.os.Bundle; -import io.flutter.app.FlutterActivity; -import io.flutter.plugins.GeneratedPluginRegistrant; +import io.flutter.embedding.android.FlutterActivity; public class MainActivity extends FlutterActivity { - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - GeneratedPluginRegistrant.registerWith(this); - } + + } diff --git a/example/ios/Flutter/flutter_export_environment.sh b/example/ios/Flutter/flutter_export_environment.sh index 3fd2a96..415ea75 100755 --- a/example/ios/Flutter/flutter_export_environment.sh +++ b/example/ios/Flutter/flutter_export_environment.sh @@ -1,12 +1,10 @@ #!/bin/sh # This is a generated file; do not edit or check into version control. -export "FLUTTER_ROOT=/Users/silvertree/Documents/dev/flutter" -export "FLUTTER_APPLICATION_PATH=/Users/silvertree/Documents/codes/dio-http-cache/example" -export "FLUTTER_TARGET=lib/main.dart" +export "FLUTTER_ROOT=D:\Users\shina\Desenvolvimento\flutter" +export "FLUTTER_APPLICATION_PATH=D:\Users\shina\Desenvolvimento\flutter_projecs\dio-http-cache\example" +export "FLUTTER_TARGET=lib\main.dart" export "FLUTTER_BUILD_DIR=build" -export "SYMROOT=${SOURCE_ROOT}/../build/ios" -export "OTHER_LDFLAGS=$(inherited) -framework Flutter" -export "FLUTTER_FRAMEWORK_DIR=/Users/silvertree/Documents/dev/flutter/bin/cache/artifacts/engine/ios" +export "SYMROOT=${SOURCE_ROOT}/../build\ios" export "FLUTTER_BUILD_NAME=1.0.0" export "FLUTTER_BUILD_NUMBER=1" export "DART_OBFUSCATION=false" diff --git a/lib/src/builder_dio.dart b/lib/src/builder_dio.dart index 976b2fb..faad6f9 100644 --- a/lib/src/builder_dio.dart +++ b/lib/src/builder_dio.dart @@ -4,11 +4,11 @@ import 'package:dio_http_cache/src/manager_dio.dart'; /// try to get maxAge and maxStale from response headers. /// local settings will always overview the value get from service. Options buildServiceCacheOptions( - {Options options, - Duration maxStale, - String primaryKey, - String subKey, - bool forceRefresh}) => + {Options? options, + Duration? maxStale, + String? primaryKey, + String? subKey, + bool? forceRefresh}) => buildConfigurableCacheOptions( options: options, maxStale: maxStale, @@ -18,11 +18,11 @@ Options buildServiceCacheOptions( /// build a normal cache options Options buildCacheOptions(Duration maxAge, - {Duration maxStale, - String primaryKey, - String subKey, - Options options, - bool forceRefresh}) => + {Duration? maxStale, + String? primaryKey, + String? subKey, + Options? options, + bool? forceRefresh}) => buildConfigurableCacheOptions( maxAge: maxAge, options: options, @@ -34,32 +34,32 @@ Options buildCacheOptions(Duration maxAge, /// if null==maxAge, will try to get maxAge and maxStale from response headers. /// local settings will always overview the value get from service. Options buildConfigurableCacheOptions( - {Options options, - Duration maxAge, - Duration maxStale, - String primaryKey, - String subKey, - bool forceRefresh}) { - if (null == options) { - options = Options(); + {Options? options, + Duration? maxAge, + Duration? maxStale, + String? primaryKey, + String? subKey, + bool? forceRefresh}) { + if (options == null) { + options = Options(extra: {}); } else if (options.responseType == ResponseType.stream) { throw Exception("ResponseType.stream is not supported"); } - options.extra.addAll({DIO_CACHE_KEY_TRY_CACHE: true}); + options.extra?.addAll({DIO_CACHE_KEY_TRY_CACHE: true}); if (null != maxAge) { - options.extra.addAll({DIO_CACHE_KEY_MAX_AGE: maxAge}); + options.extra?.addAll({DIO_CACHE_KEY_MAX_AGE: maxAge}); } if (null != maxStale) { - options.extra.addAll({DIO_CACHE_KEY_MAX_STALE: maxStale}); + options.extra?.addAll({DIO_CACHE_KEY_MAX_STALE: maxStale}); } if (null != primaryKey) { - options.extra.addAll({DIO_CACHE_KEY_PRIMARY_KEY: primaryKey}); + options.extra?.addAll({DIO_CACHE_KEY_PRIMARY_KEY: primaryKey}); } if (null != subKey) { - options.extra.addAll({DIO_CACHE_KEY_SUB_KEY: subKey}); + options.extra?.addAll({DIO_CACHE_KEY_SUB_KEY: subKey}); } if (null != forceRefresh) { - options.extra.addAll({DIO_CACHE_KEY_FORCE_REFRESH: forceRefresh}); + options.extra?.addAll({DIO_CACHE_KEY_FORCE_REFRESH: forceRefresh}); } return options; } diff --git a/lib/src/core/config.dart b/lib/src/core/config.dart index a4a87cb..706d7bb 100644 --- a/lib/src/core/config.dart +++ b/lib/src/core/config.dart @@ -5,10 +5,10 @@ typedef Future> Decrypt(List str); class CacheConfig { final Duration defaultMaxAge; - final Duration defaultMaxStale; - final String databasePath; + final Duration? defaultMaxStale; + final String? databasePath; final String databaseName; - final String baseUrl; + final String? baseUrl; final String defaultRequestMethod; final bool skipMemoryCache; @@ -16,9 +16,9 @@ class CacheConfig { final int maxMemoryCacheCount; - final Encrypt encrypt; - final Decrypt decrypt; - final ICacheStore diskStore; + final Encrypt? encrypt; + final Decrypt? decrypt; + final ICacheStore? diskStore; CacheConfig( {this.defaultMaxAge = const Duration(days: 7), diff --git a/lib/src/core/manager.dart b/lib/src/core/manager.dart index bd1d4e1..7cc306d 100644 --- a/lib/src/core/manager.dart +++ b/lib/src/core/manager.dart @@ -10,10 +10,10 @@ import 'package:sqflite/utils/utils.dart'; class CacheManager { CacheConfig _config; - ICacheStore _diskCacheStore; - ICacheStore _memoryCacheStore; - MD5 _md5; - Utf8Encoder _utf8encoder; + ICacheStore? _diskCacheStore; + ICacheStore? _memoryCacheStore; + late Hash _md5; + late Utf8Encoder _utf8encoder; CacheManager(this._config) { _md5 = md5; @@ -26,7 +26,7 @@ class CacheManager { _memoryCacheStore = MemoryCacheStore(_config.maxMemoryCacheCount); } - Future _pullFromCache(String key, {String subKey}) async { + Future _pullFromCache(String key, {String? subKey}) async { key = _convertMd5(key); if (null != subKey) subKey = _convertMd5(subKey); var obj = await _memoryCacheStore?.getCacheObj(key, subKey: subKey); @@ -36,15 +36,15 @@ class CacheManager { } if (null != obj) { var now = DateTime.now().millisecondsSinceEpoch; - if (null != obj.maxStaleDate && obj.maxStaleDate > 0) { + if (null != obj.maxStaleDate && obj.maxStaleDate! > 0) { //if maxStaleDate exist, Remove it if maxStaleDate expired. - if (obj.maxStaleDate < now) { + if (obj.maxStaleDate! < now) { await delete(key, subKey: subKey); return null; } } else { //if maxStaleDate NOT exist, Remove it if maxAgeDate expired. - if (obj.maxAgeDate < now) { + if (obj.maxAgeDate! < now) { await delete(key, subKey: subKey); return null; } @@ -53,33 +53,33 @@ class CacheManager { return obj; } - Future pullFromCacheBeforeMaxAge(String key, - {String subKey}) async { + Future pullFromCacheBeforeMaxAge(String key, + {String? subKey}) async { var obj = await _pullFromCache(key, subKey: subKey); if (null != obj && null != obj.maxAgeDate && - obj.maxAgeDate < DateTime.now().millisecondsSinceEpoch) { + obj.maxAgeDate! < DateTime.now().millisecondsSinceEpoch) { return null; } return obj; } - Future pullFromCacheBeforeMaxStale(String key, - {String subKey}) async { + Future pullFromCacheBeforeMaxStale(String key, + {String? subKey}) async { return await _pullFromCache(key, subKey: subKey); } Future pushToCache(CacheObj obj) { - obj.key = _convertMd5(obj.key); - if (null != obj.subKey) obj.subKey = _convertMd5(obj.subKey); + obj.key = _convertMd5(obj.key!); + if (null != obj.subKey) obj.subKey = _convertMd5(obj.subKey!); - if (null == obj.maxAgeDate || obj.maxAgeDate <= 0) { + if (null == obj.maxAgeDate || obj.maxAgeDate! <= 0) { obj.maxAge = _config.defaultMaxAge; } - if (null == obj.maxAgeDate || obj.maxAgeDate <= 0) { + if (null == obj.maxAgeDate || obj.maxAgeDate! <= 0) { return Future.value(false); } - if ((null == obj.maxStaleDate || obj.maxStaleDate <= 0) && + if ((null == obj.maxStaleDate || obj.maxStaleDate! <= 0) && null != _config.defaultMaxStale) { obj.maxStale = _config.defaultMaxStale; } @@ -88,7 +88,7 @@ class CacheManager { _memoryCacheStore?.setCacheObj(obj), _diskCacheStore?.setCacheObj(obj)); } - Future delete(String key, {String subKey}) { + Future delete(String key, {String? subKey}) { key = _convertMd5(key); if (null != subKey) subKey = _convertMd5(subKey); @@ -114,12 +114,12 @@ class CacheManager { } Future _getCacheFutureResult( - ICacheStore memoryCacheStore, - ICacheStore diskCacheStore, - Future memoryCacheFuture, - Future diskCacheFuture) async { - var result1 = (null == memoryCacheStore) ? true : (await memoryCacheFuture); - var result2 = (null == diskCacheStore) ? true : (await diskCacheFuture); + ICacheStore? memoryCacheStore, + ICacheStore? diskCacheStore, + Future? memoryCacheFuture, + Future? diskCacheFuture) async { + var result1 = (null == memoryCacheStore) ? true : (await memoryCacheFuture!); + var result2 = (null == diskCacheStore) ? true : (await diskCacheFuture!); return result1 && result2; } } diff --git a/lib/src/core/obj.dart b/lib/src/core/obj.dart index 6527f89..994b066 100644 --- a/lib/src/core/obj.dart +++ b/lib/src/core/obj.dart @@ -4,35 +4,35 @@ part 'obj.g.dart'; @JsonSerializable() class CacheObj { - String key; - String subKey; + String? key; + String? subKey; @JsonKey(name: "max_age_date") - int maxAgeDate; + int? maxAgeDate; @JsonKey(name: "max_stale_date") - int maxStaleDate; - List content; - int statusCode; - List headers; + int? maxStaleDate; + List? content; + int? statusCode; + List? headers; CacheObj._( this.key, this.subKey, this.content, this.statusCode, this.headers); - factory CacheObj(String key, List content, - {String subKey = "", - Duration maxAge, - Duration maxStale, - int statusCode = 200, - List headers}) { + factory CacheObj(String? key, List? content, + {String? subKey = "", + Duration? maxAge, + Duration? maxStale, + int? statusCode = 200, + List? headers}) { return CacheObj._(key, subKey, content, statusCode, headers) ..maxAge = maxAge ..maxStale = maxStale; } - set maxAge(Duration duration) { + set maxAge(Duration? duration) { if (null != duration) this.maxAgeDate = _convertDuration(duration); } - set maxStale(Duration duration) { + set maxStale(Duration? duration) { if (null != duration) this.maxStaleDate = _convertDuration(duration); } diff --git a/lib/src/core/obj.g.dart b/lib/src/core/obj.g.dart index 74a2ae4..e54f123 100644 --- a/lib/src/core/obj.g.dart +++ b/lib/src/core/obj.g.dart @@ -8,14 +8,14 @@ part of 'obj.dart'; CacheObj _$CacheObjFromJson(Map json) { return CacheObj( - json['key'] as String, - (json['content'] as List)?.map((e) => e as int)?.toList(), - subKey: json['subKey'] as String, - statusCode: json['statusCode'] as int, - headers: (json['headers'] as List)?.map((e) => e as int)?.toList(), + json['key'] as String?, + (json['content'] as List?)?.map((e) => e as int)?.toList(), + subKey: json['subKey'] as String?, + statusCode: json['statusCode'] as int?, + headers: (json['headers'] as List?)?.map((e) => e as int)?.toList(), ) - ..maxAgeDate = json['max_age_date'] as int - ..maxStaleDate = json['max_stale_date'] as int; + ..maxAgeDate = json['max_age_date'] as int? + ..maxStaleDate = json['max_stale_date'] as int?; } Map _$CacheObjToJson(CacheObj instance) => { diff --git a/lib/src/manager_dio.dart b/lib/src/manager_dio.dart index 33e8af7..86e45d3 100644 --- a/lib/src/manager_dio.dart +++ b/lib/src/manager_dio.dart @@ -15,13 +15,13 @@ const DIO_CACHE_KEY_FORCE_REFRESH = "dio_cache_force_refresh"; const DIO_CACHE_HEADER_KEY_DATA_SOURCE = "dio_cache_header_key_data_source"; typedef _ParseHeadCallback = void Function( - Duration _maxAge, Duration _maxStale); + Duration? _maxAge, Duration? _maxStale); class DioCacheManager { - CacheManager _manager; - InterceptorsWrapper _interceptor; - String _baseUrl; - String _defaultRequestMethod; + CacheManager? _manager; + InterceptorsWrapper? _interceptor; + String? _baseUrl; + String? _defaultRequestMethod; DioCacheManager(CacheConfig config) { _manager = CacheManager(config); @@ -48,41 +48,42 @@ class DioCacheManager { var responseDataFromCache = await _pullFromCacheBeforeMaxAge(options); if (null != responseDataFromCache) { return _buildResponse( - responseDataFromCache, responseDataFromCache?.statusCode, options); + responseDataFromCache, responseDataFromCache.statusCode, options); } return options; } _onResponse(Response response) async { if ((response.request.extra[DIO_CACHE_KEY_TRY_CACHE] ?? false) == true && - response.statusCode >= 200 && - response.statusCode < 300) { + response.statusCode! >= 200 && + response.statusCode! < 300) { await _pushToCache(response); } return response; } _onError(DioError e) async { - if ((e.request.extra[DIO_CACHE_KEY_TRY_CACHE] ?? false) == true) { - var responseDataFromCache = await _pullFromCacheBeforeMaxStale(e.request); + if ((e.request!.extra[DIO_CACHE_KEY_TRY_CACHE] ?? false) == true) { + var responseDataFromCache = + await _pullFromCacheBeforeMaxStale(e.request!); if (null != responseDataFromCache) return _buildResponse(responseDataFromCache, - responseDataFromCache?.statusCode, e.request); + responseDataFromCache.statusCode, e.request!); } return e; } Response _buildResponse( - CacheObj obj, int statusCode, RequestOptions options) { - Headers headers; + CacheObj obj, int? statusCode, RequestOptions options) { + Headers? headers; if (null != obj.headers) { headers = Headers.fromMap((Map>.from( - jsonDecode(utf8.decode(obj.headers)))) + jsonDecode(utf8.decode(obj.headers!)))) .map((k, v) => MapEntry(k, List.from(v)))); } if (null == headers) { headers = Headers(); - options.headers.forEach((k, v) => headers.add(k, v ?? "")); + options.headers.forEach((k, v) => headers!.add(k, v ?? "")); } // add flag headers.add(DIO_CACHE_HEADER_KEY_DATA_SOURCE, "from_cache"); @@ -91,35 +92,37 @@ class DioCacheManager { data = jsonDecode(utf8.decode(data)); } return Response( - data: data, - headers: headers, - extra: options.extra..remove(DIO_CACHE_KEY_TRY_CACHE), - statusCode: statusCode ?? 200); + data: data, + headers: headers, + extra: options.extra..remove(DIO_CACHE_KEY_TRY_CACHE), + statusCode: statusCode ?? 200, + request: options, + ); } - Future _pullFromCacheBeforeMaxAge(RequestOptions options) { + Future? _pullFromCacheBeforeMaxAge(RequestOptions options) { return _manager?.pullFromCacheBeforeMaxAge( _getPrimaryKeyFromOptions(options), subKey: _getSubKeyFromOptions(options)); } - Future _pullFromCacheBeforeMaxStale(RequestOptions options) { + Future? _pullFromCacheBeforeMaxStale(RequestOptions options) { return _manager?.pullFromCacheBeforeMaxStale( _getPrimaryKeyFromOptions(options), subKey: _getSubKeyFromOptions(options)); } - Future _pushToCache(Response response) { + Future? _pushToCache(Response response) { RequestOptions options = response.request; - Duration maxAge = options.extra[DIO_CACHE_KEY_MAX_AGE]; - Duration maxStale = options.extra[DIO_CACHE_KEY_MAX_STALE]; + Duration? maxAge = options.extra[DIO_CACHE_KEY_MAX_AGE]; + Duration? maxStale = options.extra[DIO_CACHE_KEY_MAX_STALE]; if (null == maxAge) { _tryParseHead(response, maxStale, (_maxAge, _maxStale) { maxAge = _maxAge; maxStale = _maxStale; }); } - List data; + List? data; if (options.responseType == ResponseType.bytes) { data = response.data; } else { @@ -136,8 +139,8 @@ class DioCacheManager { // try to get maxAge and maxStale from http headers void _tryParseHead( - Response response, Duration maxStale, _ParseHeadCallback callback) { - Duration _maxAge; + Response response, Duration? maxStale, _ParseHeadCallback callback) { + Duration? _maxAge; var cacheControl = response.headers.value(HttpHeaders.cacheControlHeader); if (null != cacheControl) { // try to get maxAge and maxStale from cacheControl @@ -163,7 +166,7 @@ class DioCacheManager { // try to get maxAge from expires var expires = response.headers.value(HttpHeaders.expiresHeader); if (null != expires && expires.length > 4) { - DateTime endTime; + DateTime? endTime; try { endTime = HttpDate.parse(expires).toLocal(); } catch (e) { @@ -177,9 +180,10 @@ class DioCacheManager { callback(_maxAge, maxStale); } - Duration _tryGetDurationFromMap(Map parameters, String key) { + Duration? _tryGetDurationFromMap( + Map? parameters, String key) { if (null != parameters && parameters.containsKey(key)) { - var value = int.tryParse(parameters[key]); + var value = int.tryParse(parameters[key]!); if (null != value && value >= 0) { return Duration(seconds: value); } @@ -195,52 +199,52 @@ class DioCacheManager { return "${_getRequestMethod(options.method)}-$primaryKey"; } - String _getRequestMethod(String requestMethod) { + String _getRequestMethod(String? requestMethod) { if (null != requestMethod && requestMethod.length > 0) { return requestMethod.toUpperCase(); } - if (null != _defaultRequestMethod && _defaultRequestMethod.length > 0) { - return _defaultRequestMethod.toUpperCase(); + if (null != _defaultRequestMethod && _defaultRequestMethod!.length > 0) { + return _defaultRequestMethod!.toUpperCase(); } return "DEFAULT_METHOD"; } - String _getSubKeyFromOptions(RequestOptions options) { + String? _getSubKeyFromOptions(RequestOptions options) { return options.extra.containsKey(DIO_CACHE_KEY_SUB_KEY) ? options.extra[DIO_CACHE_KEY_SUB_KEY] : _getSubKeyFromUri(options.uri, data: options.data); } - String _getPrimaryKeyFromUri(Uri uri) => "${uri?.host}${uri?.path}"; + String _getPrimaryKeyFromUri(Uri uri) => "${uri.host}${uri.path}"; String _getSubKeyFromUri(Uri uri, {dynamic data}) => - "${data?.toString()}_${uri?.query}"; + "${data?.toString()}_${uri.query}"; /// delete local cache by primaryKey and optional subKey - Future delete(String primaryKey, - {String requestMethod, String subKey}) => + Future? delete(String primaryKey, + {String? requestMethod, String? subKey}) => _manager?.delete("${_getRequestMethod(requestMethod)}-$primaryKey", subKey: subKey); /// no matter what subKey is, delete local cache if primary matched. - Future deleteByPrimaryKeyWithUri(Uri uri, {String requestMethod}) => + Future? deleteByPrimaryKeyWithUri(Uri uri, {String? requestMethod}) => delete(_getPrimaryKeyFromUri(uri), requestMethod: requestMethod); - Future deleteByPrimaryKey(String path, {String requestMethod}) => + Future? deleteByPrimaryKey(String path, {String? requestMethod}) => deleteByPrimaryKeyWithUri(_getUriByPath(_baseUrl, path), requestMethod: requestMethod); /// delete local cache when both primaryKey and subKey matched. - Future deleteByPrimaryKeyAndSubKeyWithUri(Uri uri, - {String requestMethod, String subKey, dynamic data}) => + Future? deleteByPrimaryKeyAndSubKeyWithUri(Uri uri, + {String? requestMethod, String? subKey, dynamic data}) => delete(_getPrimaryKeyFromUri(uri), requestMethod: requestMethod, subKey: subKey ?? _getSubKeyFromUri(uri, data: data)); - Future deleteByPrimaryKeyAndSubKey(String path, - {String requestMethod, - Map queryParameters, - String subKey, + Future? deleteByPrimaryKeyAndSubKey(String path, + {String? requestMethod, + Map? queryParameters, + String? subKey, dynamic data}) => deleteByPrimaryKeyAndSubKeyWithUri( _getUriByPath(_baseUrl, path, @@ -250,13 +254,13 @@ class DioCacheManager { data: data); /// clear all expired cache. - Future clearExpired() => _manager?.clearExpired(); + Future? clearExpired() => _manager?.clearExpired(); /// empty local cache. - Future clearAll() => _manager?.clearAll(); + Future? clearAll() => _manager?.clearAll(); - Uri _getUriByPath(String baseUrl, String path, - {dynamic data, Map queryParameters}) { + Uri _getUriByPath(String? baseUrl, String path, + {dynamic data, Map? queryParameters}) { if (!path.startsWith(RegExp(r"https?:"))) { assert(null != baseUrl && baseUrl.length > 0); } diff --git a/lib/src/store/store_disk.dart b/lib/src/store/store_disk.dart index d81ea53..740094c 100644 --- a/lib/src/store/store_disk.dart +++ b/lib/src/store/store_disk.dart @@ -7,10 +7,10 @@ import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; class DiskCacheStore extends ICacheStore { - final String _databasePath; + final String? _databasePath; final String _databaseName; - final Encrypt _encrypt; - final Decrypt _decrypt; + final Encrypt? _encrypt; + final Decrypt? _decrypt; final String _tableCacheObject = "cache_dio"; final String _columnKey = "key"; final String _columnSubKey = "subKey"; @@ -20,16 +20,16 @@ class DiskCacheStore extends ICacheStore { final String _columnStatusCode = "statusCode"; final String _columnHeaders = "headers"; - Database _db; + Database? _db; static const int _curDBVersion = 3; - Future get _database async { + Future get _database async { if (null == _db) { var path = _databasePath; if (null == path || path.length <= 0) { path = await getDatabasesPath(); } - await Directory(path).create(recursive: true); + await Directory(path!).create(recursive: true); path = join(path, "$_databaseName.db"); _db = await openDatabase(path, version: _curDBVersion, @@ -41,7 +41,7 @@ class DiskCacheStore extends ICacheStore { return _db; } - _tryFixDbNoVersionBug(Database db, String dbPath) async { + _tryFixDbNoVersionBug(Database db, String? dbPath) async { if ((await db.getVersion()) == 0) { var isTableUserLogExist = await db .rawQuery( @@ -70,7 +70,7 @@ class DiskCacheStore extends ICacheStore { await db.execute(_getCreateTableSql()); } - List> _dbUpgradeList() => [ + List?> _dbUpgradeList() => [ // 0 -> 1 null, // 1 -> 2 @@ -108,7 +108,7 @@ class DiskCacheStore extends ICacheStore { : super(); @override - Future getCacheObj(String key, {String subKey}) async { + Future getCacheObj(String key, {String? subKey}) async { var db = await _database; if (null == db) return null; var where = "$_columnKey=\"$key\""; @@ -140,7 +140,7 @@ class DiskCacheStore extends ICacheStore { } @override - Future delete(String key, {String subKey}) async { + Future delete(String key, {String? subKey}) async { var db = await _database; if (null == db) return false; var where = "$_columnKey=\"$key\""; @@ -154,7 +154,7 @@ class DiskCacheStore extends ICacheStore { return _clearExpired(db); } - Future _clearExpired(Database db) async { + Future _clearExpired(Database? db) async { if (null == db) return false; var now = DateTime.now().millisecondsSinceEpoch; var where1 = "$_columnMaxStaleDate > 0 and $_columnMaxStaleDate < $now"; @@ -176,18 +176,18 @@ class DiskCacheStore extends ICacheStore { return obj; } - Future> _decryptCacheStr(List bytes) async { + Future?> _decryptCacheStr(List? bytes) async { if (null == bytes) return null; if (null != _decrypt) { - bytes = await _decrypt(bytes); + bytes = await _decrypt!(bytes); } return bytes; } - Future> _encryptCacheStr(List bytes) async { + Future?> _encryptCacheStr(List? bytes) async { if (null == bytes) return null; if (null != _encrypt) { - bytes = await _encrypt(bytes); + bytes = await _encrypt!(bytes); } return bytes; } diff --git a/lib/src/store/store_impl.dart b/lib/src/store/store_impl.dart index 35c7e2f..d3e29bd 100644 --- a/lib/src/store/store_impl.dart +++ b/lib/src/store/store_impl.dart @@ -3,11 +3,11 @@ import 'package:dio_http_cache/src/core/obj.dart'; abstract class ICacheStore { ICacheStore(); - Future getCacheObj(String key, {String subKey}); + Future getCacheObj(String key, {String? subKey}); Future setCacheObj(CacheObj obj); - Future delete(String key, {String subKey}); + Future delete(String key, {String? subKey}); Future clearExpired(); diff --git a/lib/src/store/store_memory.dart b/lib/src/store/store_memory.dart index cb353b0..0411788 100644 --- a/lib/src/store/store_memory.dart +++ b/lib/src/store/store_memory.dart @@ -6,8 +6,8 @@ import 'package:quiver/cache.dart'; class MemoryCacheStore extends ICacheStore { final int _maxMemoryCacheCount; - MapCache _mapCache; - Map> _keys; + MapCache? _mapCache; + Map>? _keys; MemoryCacheStore(this._maxMemoryCacheCount) : super() { _initMap(); @@ -19,20 +19,21 @@ class MemoryCacheStore extends ICacheStore { } @override - Future getCacheObj(String key, {String subKey = ""}) async => - _mapCache.get("${key}_$subKey"); + Future getCacheObj(String key, {String? subKey = ""}) async => + _mapCache!.get("${key}_$subKey"); @override Future setCacheObj(CacheObj obj) async { - _mapCache.set("${obj.key}_${obj.subKey}", obj); + _mapCache!.set("${obj.key}_${obj.subKey}", obj); _storeKey(obj); return true; } @override - Future delete(String key, {String subKey}) async { + Future delete(String key, {String? subKey}) async { // _mapCache.invalidate("${key}_${subKey ?? ""}"); - _removeKey(key, subKey: subKey).forEach((key) => _mapCache.invalidate(key)); + _removeKey(key, subKey: subKey) + .forEach((key) => _mapCache!.invalidate(key)); return true; } @@ -50,21 +51,21 @@ class MemoryCacheStore extends ICacheStore { } _storeKey(CacheObj obj) { - List subKeyList = _keys[obj.key]; - if (null == subKeyList) subKeyList = List(); + List? subKeyList = _keys![obj.key]; + if (null == subKeyList) subKeyList = []; subKeyList.add(obj.subKey ?? ""); - _keys[obj.key] = subKeyList; + _keys![obj.key] = subKeyList; } - List _removeKey(String key, {String subKey}) { - List subKeyList = _keys[key]; + List _removeKey(String key, {String? subKey}) { + List? subKeyList = _keys![key]; if (null == subKeyList || subKeyList.length <= 0) return []; if (null == subKey) { - _keys.remove(key); + _keys!.remove(key); return subKeyList.map((sKey) => "${key}_$sKey").toList(); } else { subKeyList.remove(subKey); - _keys[key] = subKeyList; + _keys![key] = subKeyList; return ["${key}_$subKey"]; } } diff --git a/pubspec.yaml b/pubspec.yaml index ce92ccf..75e8039 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,28 +1,28 @@ name: dio_http_cache description: http cache lib for Flutter dio like RxCache.It use sqflite as disk cache,and google/quiver-dart/LRU strategy as memory cache. -version: 0.2.11 +version: 0.3.0 authors: - Hurshi homepage: https://github.com/hurshi/dio-http-cache environment: - sdk: ">=2.1.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: sdk: flutter - quiver: ^2.0.3 - json_serializable: ^3.0.0 - json_annotation: ^3.0.0 - dio: ^3.0.1 - sqflite: ^1.1.6+3 - path: ^1.6.2 - crypto: ^2.1.1+1 + quiver: ^3.0.0 + json_serializable: ^4.0.2 + json_annotation: ^4.0.0 + dio: ^4.0.0-beta4 + sqflite: ^2.0.0+1 + path: ^1.8.0 + crypto: ^3.0.0 dev_dependencies: flutter_test: sdk: flutter - build_runner: ^1.6.6 + build_runner: ^1.11.5 flutter: module: