43 lines
1.4 KiB
Dart
43 lines
1.4 KiB
Dart
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<void> 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<Mappable>,内部自动转 Map
|
|
static Future<void> cache<T extends Mappable>(String warehouse, List<T> data) async {
|
|
List<Map<String, dynamic>> 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<Mappable>,需要传入 fromMap 函数
|
|
static Future<List<T>?> getCache<T>(String warehouse, T Function(Map<String, dynamic>) fromMap) async {
|
|
List? mapList = box.get(warehouse) as List?;
|
|
if (mapList == null) return null;
|
|
|
|
return mapList.map((e) => fromMap(Map<String, dynamic>.from(e))).toList();
|
|
}
|
|
|
|
}
|