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 isPreloadEnabled() async { final prefs = await SharedPreferences.getInstance(); return prefs.getBool(_preloadEnabledKey) ?? true; } /// 设置预加载开关状态 Future setPreloadEnabled(bool enabled) async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(_preloadEnabledKey, enabled); } /// 缓存排行榜数据 Future cachePopularList( String type, List> 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>?> 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>(); } } catch (e) { print('解析缓存数据失败: $e'); } return null; } /// 获取缓存时间戳 Future getCacheTimestamp(String type) async { final prefs = await SharedPreferences.getInstance(); final key = '${_popularListCachePrefix}${type}_timestamp'; return prefs.getInt(key); } /// 清除指定类型的缓存 Future clearCache(String type) async { final prefs = await SharedPreferences.getInstance(); final key = _popularListCachePrefix + type; await prefs.remove(key); await prefs.remove('${key}_timestamp'); } /// 清除所有排行榜缓存 Future clearAllPopularCache() async { final prefs = await SharedPreferences.getInstance(); final keys = prefs.getKeys(); for (final key in keys) { if (key.startsWith(_popularListCachePrefix)) { await prefs.remove(key); } } } }