91 lines
2.7 KiB
Dart
91 lines
2.7 KiB
Dart
import 'dart:convert';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
/// 时间: 2026-03-30
|
|
/// 功能: 本地缓存管理器
|
|
/// 介绍: 管理应用的本地缓存数据,包括排行榜数据等
|
|
/// 最新变化: 新建本地缓存管理器
|
|
|
|
class LocalCacheManager {
|
|
static final LocalCacheManager _instance = LocalCacheManager._internal();
|
|
factory LocalCacheManager() => _instance;
|
|
LocalCacheManager._internal();
|
|
|
|
static const String _preloadEnabledKey = 'preload_enabled';
|
|
static const String _popularListCachePrefix = 'popular_list_cache_';
|
|
|
|
/// 获取预加载开关状态
|
|
Future<bool> isPreloadEnabled() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
return prefs.getBool(_preloadEnabledKey) ?? true;
|
|
}
|
|
|
|
/// 设置预加载开关状态
|
|
Future<void> setPreloadEnabled(bool enabled) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setBool(_preloadEnabledKey, enabled);
|
|
}
|
|
|
|
/// 缓存排行榜数据
|
|
Future<void> cachePopularList(
|
|
String type,
|
|
List<Map<String, dynamic>> data,
|
|
) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final key = _popularListCachePrefix + type;
|
|
final jsonData = jsonEncode(data);
|
|
await prefs.setString(key, jsonData);
|
|
|
|
final timestampKey = '${key}_timestamp';
|
|
await prefs.setInt(timestampKey, DateTime.now().millisecondsSinceEpoch);
|
|
}
|
|
|
|
/// 获取缓存的排行榜数据
|
|
Future<List<Map<String, dynamic>>?> getCachedPopularList(String type) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final key = _popularListCachePrefix + type;
|
|
final jsonData = prefs.getString(key);
|
|
|
|
if (jsonData == null) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
final decoded = jsonDecode(jsonData);
|
|
if (decoded is List) {
|
|
return decoded.cast<Map<String, dynamic>>();
|
|
}
|
|
} catch (e) {
|
|
// 解析失败
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// 获取缓存时间戳
|
|
Future<int?> getCacheTimestamp(String type) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final key = '${_popularListCachePrefix}${type}_timestamp';
|
|
return prefs.getInt(key);
|
|
}
|
|
|
|
/// 清除指定类型的缓存
|
|
Future<void> clearCache(String type) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final key = _popularListCachePrefix + type;
|
|
await prefs.remove(key);
|
|
await prefs.remove('${key}_timestamp');
|
|
}
|
|
|
|
/// 清除所有排行榜缓存
|
|
Future<void> clearAllPopularCache() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final keys = prefs.getKeys();
|
|
for (final key in keys) {
|
|
if (key.startsWith(_popularListCachePrefix)) {
|
|
await prefs.remove(key);
|
|
}
|
|
}
|
|
}
|
|
}
|