import 'dart:async'; import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:sino_med_cloud/core/constants/app_constants.dart'; /// 本地存储管理类 class LocalStorage { static SharedPreferences? _prefs; static Completer? _initCompleter; /// 初始化本地存储 static Future init() async { if (_prefs != null) { return; } _prefs = await SharedPreferences.getInstance(); _initCompleter?.complete(); _initCompleter = null; } /// 确保已初始化(自动初始化,如果未初始化则初始化) static Future _ensureInitialized() async { if (_prefs != null) { return; } // 如果正在初始化,等待初始化完成 if (_initCompleter != null) { await _initCompleter!.future; return; } // 开始初始化 _initCompleter = Completer(); await init(); } /// 获取 SharedPreferences 实例(内部使用) static Future get _prefsAsync async { await _ensureInitialized(); return _prefs!; } // ==================== String 操作 ==================== /// 保存字符串 static Future setString(String key, String value) async { final prefs = await _prefsAsync; return await prefs.setString(key, value); } /// 获取字符串 static Future getString(String key, {String? defaultValue}) async { final prefs = await _prefsAsync; return prefs.getString(key) ?? defaultValue; } // ==================== Int 操作 ==================== /// 保存整数 static Future setInt(String key, int value) async { final prefs = await _prefsAsync; return await prefs.setInt(key, value); } /// 获取整数 static Future getInt(String key, {int? defaultValue}) async { final prefs = await _prefsAsync; return prefs.getInt(key) ?? defaultValue; } // ==================== Double 操作 ==================== /// 保存浮点数 static Future setDouble(String key, double value) async { final prefs = await _prefsAsync; return await prefs.setDouble(key, value); } /// 获取浮点数 static Future getDouble(String key, {double? defaultValue}) async { final prefs = await _prefsAsync; return prefs.getDouble(key) ?? defaultValue; } // ==================== Bool 操作 ==================== /// 保存布尔值 static Future setBool(String key, bool value) async { final prefs = await _prefsAsync; return await prefs.setBool(key, value); } /// 获取布尔值 static Future getBool(String key, {bool? defaultValue}) async { final prefs = await _prefsAsync; return prefs.getBool(key) ?? defaultValue; } // ==================== StringList 操作 ==================== /// 保存字符串列表 static Future setStringList(String key, List value) async { final prefs = await _prefsAsync; return await prefs.setStringList(key, value); } /// 获取字符串列表 static Future?> getStringList(String key) async { final prefs = await _prefsAsync; return prefs.getStringList(key); } // ==================== Map 操作 ==================== /// 保存键值对(Map) /// /// [key] 存储的键 /// [value] 要保存的 Map 对象 /// /// 返回保存是否成功 /// /// 示例: /// ```dart /// await LocalStorage.setMap('user', {'name': 'John', 'age': 30}); /// ``` static Future setMap(String key, Map value) async { try { // 将 Map 转换为 JSON 字符串保存 final jsonString = jsonEncode(value); final prefs = await _prefsAsync; return await prefs.setString(key, jsonString); } catch (e) { // 如果转换失败,返回 false return false; } } /// 获取键值对(Map) /// /// [key] 存储的键 /// [defaultValue] 默认值(可选) /// /// 返回 Map 对象,如果不存在或解析失败则返回 null 或默认值 /// /// 示例: /// ```dart /// final user = await LocalStorage.getMap('user'); /// // 返回:{'name': 'John', 'age': 30} /// ``` static Future?> getMap(String key, {Map? defaultValue}) async { try { final prefs = await _prefsAsync; final jsonString = prefs.getString(key); if (jsonString == null) { return defaultValue; } // 将 JSON 字符串解析为 Map final decoded = jsonDecode(jsonString) as Map; return decoded; } catch (e) { // 如果解析失败,返回默认值或 null return defaultValue; } } // ==================== List 操作 ==================== /// 保存列表(List>) /// /// [key] 存储的键 /// [value] 要保存的列表对象 /// /// 返回保存是否成功 /// /// 示例: /// ```dart /// await LocalStorage.setList('institutions', [ /// {'id': 10, 'name': '机构1'}, /// {'id': 20, 'name': '机构2'}, /// ]); /// ``` static Future setList(String key, List> value) async { try { // 将 List 转换为 JSON 字符串保存 final jsonString = jsonEncode(value); final prefs = await _prefsAsync; return await prefs.setString(key, jsonString); } catch (e) { // 如果转换失败,返回 false return false; } } /// 获取列表(List>) /// /// [key] 存储的键 /// [defaultValue] 默认值(可选) /// /// 返回列表对象,如果不存在或解析失败则返回 null 或默认值 /// /// 示例: /// ```dart /// final institutions = await LocalStorage.getList('institutions'); /// // 返回:[{'id': 10, 'name': '机构1'}, {'id': 20, 'name': '机构2'}] /// ``` static Future>?> getList(String key, {List>? defaultValue}) async { try { final prefs = await _prefsAsync; final jsonString = prefs.getString(key); if (jsonString == null) { return defaultValue; } // 将 JSON 字符串解析为 List final decoded = jsonDecode(jsonString) as List; // 将 List 中的每个元素转换为 Map return decoded.map((item) => item as Map).toList(); } catch (e) { // 如果解析失败,返回默认值或 null return defaultValue; } } // ==================== 通用操作 ==================== /// 删除指定 key static Future remove(String key) async { final prefs = await _prefsAsync; return await prefs.remove(key); } /// 清空所有数据 static Future clear() async { final prefs = await _prefsAsync; return await prefs.clear(); } /// 检查 key 是否存在 static Future containsKey(String key) async { final prefs = await _prefsAsync; return prefs.containsKey(key); } /// 获取所有 key static Future> getKeys() async { final prefs = await _prefsAsync; return prefs.getKeys(); } // ==================== 常用业务方法 ==================== /// 保存 Token static Future saveToken(String token) async { return await setString(AppConstants.keyToken, token); } /// 获取 Token static Future getToken() async { return await getString(AppConstants.keyToken); } /// 删除 Token static Future removeToken() async { return await remove(AppConstants.keyToken); } /// 保存用户信息(JSON 字符串) static Future saveUserInfo(Map userInfo) async { return await setMap(AppConstants.keyUserInfo, userInfo); } /// 获取用户信息 static Future?> getUserInfo() async { return await getMap(AppConstants.keyUserInfo); } /// 删除用户信息 static Future removeUserInfo() async { return await remove(AppConstants.keyUserInfo); } /// 保存机构信息列表 /// /// [institutionInfo] 机构信息列表,格式为: /// ```dart /// [ /// { /// "id": 10, /// "uuid": "38a0d1fe-c08f-11f0-88d5-0242c0a80106", /// "name": "仙豆仙豆" /// } /// ] /// ``` /// /// 返回保存是否成功 static Future saveInstitutionInfo(List> institutionInfo) async { return await setList(AppConstants.keyInstitutionInfo, institutionInfo); } /// 获取机构信息列表 /// /// 返回机构信息列表,如果不存在或解析失败则返回 null /// /// 示例: /// ```dart /// final institutionInfo = await LocalStorage.getInstitutionInfo(); /// if (institutionInfo != null) { /// for (var institution in institutionInfo) { /// print('机构名称: ${institution['name']}'); /// } /// } /// ``` static Future>?> getInstitutionInfo() async { return await getList(AppConstants.keyInstitutionInfo); } /// 删除机构信息列表 /// /// 返回删除是否成功 static Future removeInstitutionInfo() async { return await remove(AppConstants.keyInstitutionInfo); } /// 保存登录手机号 static Future savePhone(String phone) async { return await setString(AppConstants.keySavedPhone, phone); } /// 获取登录手机号 static Future getPhone() async { return await getString(AppConstants.keySavedPhone); } /// 删除登录手机号 static Future removePhone() async { return await remove(AppConstants.keySavedPhone); } /// 保存登录密码(原始密码;登录时再进行 MD5 加密) static Future savePassword(String password) async { return await setString(AppConstants.keySavedPassword, password); } /// 获取登录密码(原始密码;登录时再进行 MD5 加密) static Future getPassword() async { return await getString(AppConstants.keySavedPassword); } /// 删除登录密码 static Future removePassword() async { return await remove(AppConstants.keySavedPassword); } /// 保存是否记住密码 static Future saveRememberPassword(bool remember) async { return await setBool(AppConstants.keyRememberPassword, remember); } /// 获取是否记住密码 static Future getRememberPassword() async { return await getBool(AppConstants.keyRememberPassword, defaultValue: false) ?? false; } /// 删除是否记住密码 static Future removeRememberPassword() async { return await remove(AppConstants.keyRememberPassword); } }