feat(缓存): 添加本地缓存功能并优化网络状态提示

实现本地缓存管理器,支持预加载开关和排行榜数据缓存
优化网络状态提示文案和错误处理
移除调试日志打印,改进用户体验
This commit is contained in:
Developer
2026-03-30 04:07:31 +08:00
parent 71e853587c
commit 37a2c92a16
5 changed files with 142 additions and 12 deletions

View File

@@ -0,0 +1,90 @@
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) {
print('解析缓存数据失败: $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);
}
}
}
}