import 'dart:developer'; import 'dart:io'; import 'package:elysia/plugin/MD5.dart'; import 'package:path_provider/path_provider.dart'; import 'package:hive_flutter/hive_flutter.dart'; import '../bean/Mappable.dart'; class HiverCache { static late Box box; static Future init(String userName) async { userName = MD5(userName).toString(); final cache = await getApplicationCacheDirectory(); final cacheDir = Directory("${cache.path}/user_data/"); if (!await cacheDir.exists()) { await cacheDir.create(recursive: true); } await Hive.initFlutter(cacheDir.path.toString()); await Hive.openBox(userName); box = Hive.box(userName); } /// 存储 List,内部自动转 Map static Future cache(String warehouse, List data) async { List> mapList = data.map((e) => e.toMap()).toList(); await box.delete(warehouse); await box.flush(); await box.put(warehouse, mapList); await HiverCache.box.flush(); await HiverCache.box.compact(); } /// 获取 List,需要传入 fromMap 函数 static Future?> getCache(String warehouse, T Function(Map) fromMap) async { List? mapList = box.get(warehouse) as List?; if (mapList == null) return null; return mapList.map((e) => fromMap(Map.from(e))).toList(); } }