diff --git a/lib/data/services/storage.dart b/lib/data/services/storage.dart index 9239efa..12a4c20 100644 --- a/lib/data/services/storage.dart +++ b/lib/data/services/storage.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:get/get.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -23,6 +25,16 @@ class StorageService extends GetxService { return await _prefs.setStringList(key, value); } + Future setJSON(String key, dynamic jsonVal) { + String jsonString = jsonEncode(jsonVal); + return _prefs.setString(key, jsonString); + } + + dynamic getJSON(String key) { + String? jsonString = _prefs.getString(key); + return jsonString == null ? null : jsonDecode(jsonString); + } + String getString(String key) { return _prefs.getString(key) ?? ''; } diff --git a/lib/utils/net_cache.dart b/lib/utils/net_cache.dart index 6a1e162..1fbbbe6 100644 --- a/lib/utils/net_cache.dart +++ b/lib/utils/net_cache.dart @@ -2,6 +2,7 @@ import 'dart:collection'; import 'package:dio/dio.dart'; import 'package:news_getx/config/cache.dart'; +import 'package:news_getx/data/services/storage.dart'; class CacheObject { Response response; @@ -28,22 +29,34 @@ class NetCache extends Interceptor { void onRequest(RequestOptions options, RequestInterceptorHandler handler) { // refresh标记是否是"下拉刷新" bool refresh = options.extra['refresh'] == true; + // 是否磁盘缓存 + bool cacheDisk = options.extra['cacheDisk'] == true; + + // 如果是下拉刷新,先删除相关缓存 if (refresh) { // 如果是下拉刷新,先删除相关缓存 if (options.extra['list']) { //若是列表,则只要url中包含当前path的缓存全部删除(简单实现,并不精准) cache.removeWhere((key, value) => key.contains(options.path)); } else { + // 如果不是列表,则只删除uri相同的缓存 cacheDelete(options.uri.toString()); } + + // 删除磁盘缓存 + if (cacheDisk) { + StorageService.to.remove(options.uri.toString()); + } } // get 请求,开启缓存 if (options.extra['noCache'] != true && options.method.toLowerCase() == "get") { String key = options.extra['cacheKey'] ?? options.uri.toString(); - var ob = cache[key]; + // 策略 1 内存缓存优先,2 然后才是磁盘缓存 + var ob = cache[key]; + // 1 内存缓存 if (ob != null) { //若缓存未过期,则返回缓存内容 if ((DateTime.now().millisecondsSinceEpoch - ob.timestamp) / 1000 < @@ -58,6 +71,15 @@ class NetCache extends Interceptor { cacheDelete(key); } } + + // 2 磁盘缓存 + if (cacheDisk) { + var cacheData = StorageService.to.getJSON(key); + if (cacheData) { + handler.resolve(cacheData.response); + return; + } + } } super.onRequest(options, handler); @@ -80,7 +102,15 @@ class NetCache extends Interceptor { cacheDelete(cache.keys.first); } + // 策略:内存、磁盘都写缓存 + String key = options.extra['cacheKey'] ?? options.uri.toString(); + + // 磁盘缓存 + if (options.extra["cacheDisk"] == true) { + StorageService.to.setJSON(key, CacheObject(response)); + } + cache[key] = CacheObject(response); } }