import 'package:chicken_farm/apis/system/_dict.dart'; import 'package:chicken_farm/core/utils/storage.dart'; import 'package:chicken_farm/modes/system/dict.dart'; class DictStore { static final DictStore _instance = DictStore._internal(); static const String _localStorgeKey = 'vb_dict_'; final Map> _cache = {}; factory DictStore() => _instance; DictStore._internal(); /// 根据字典类型获取字典数据列表 /// 先从缓存中查找,如果缓存中没有则调用接口查询 Future?> getDictByType(String dictType) async { // 先从内存缓存中查找 if (_cache.containsKey(dictType)) { return _cache[dictType]; } // 再从本地存储中查找 // final cachedDict = await StorageUtils.getObject>( // '$_localStorgeKey$dictType', // ); // if (cachedDict != null) { // try { // final dictList = cachedDict // .map( // (item) => item is Map // ? DictDataModel.fromJson(item) // : null, // ) // .where((item) => item != null) // .cast() // .toList(); // _cache[dictType] = dictList; // return dictList; // } catch (e) { // // 解析失败,继续从网络获取 // } // } // 如果本地都没有,则调用接口查询 final dictData = await DictApi().getDicts(dictType); if (dictData != null) { // 存入缓存 _cache[dictType] = dictData; await StorageUtils.setObject( '$_localStorgeKey$dictType', dictData.map((e) => e.toJson()).toList(), ); return dictData; } return null; } /// 根据字典类型和值查询标签 Future getLabelByTypeAndValue(String dictType, String value) async { final dict = await getDictByTypeAndValue(dictType, value); return dict?.dictLabel.isNotEmpty == true ? dict?.dictLabel : null; } /// 根据字典类型和值查询字典项 Future getDictByTypeAndValue( String dictType, String value, ) async { final dictList = await getDictByType(dictType); if (dictList != null) { final dict = dictList.firstWhere( (element) => element.dictValue == value, orElse: () => DictDataModel( dictCode: 0, dictSort: 0, dictLabel: '', dictValue: '', dictType: dictType, ), ); // 检查是否找到了匹配的字典项 if (dict.dictCode != 0 || dict.dictLabel.isNotEmpty || dict.dictValue.isNotEmpty) { return dict; } } return null; } /// 清除指定字典类型的缓存 void clearDictCache(String dictType) { _cache.remove(dictType); //StorageUtils.remove('$_localStorgeKey$dictType'); } /// 清除所有字典缓存 void clearAll() { _cache.clear(); //StorageUtils.removeWithPrefix(_localStorgeKey); } }