增加磁盘缓存,有个问题就是会有遗留磁盘缓存未清理

This commit is contained in:
胡天 2023-07-24 14:56:01 +08:00
parent d018147931
commit 9257753a31
2 changed files with 43 additions and 1 deletions

View File

@ -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<bool> 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) ?? '';
}

View File

@ -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);
}
}