sharedstorageservice.dart 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import 'package:get/get.dart';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. /// 共享(内置)存储服务 - (建议仅用于纯Web环境)
  4. class SharedStorageService extends GetxService {
  5. SharedStorageService._();
  6. ///获取当前实例的静态属性
  7. static SharedStorageService get ins => Get.find();
  8. static late final SharedPreferences _prefs;
  9. ///共享存储服务器初始化
  10. static Future<SharedStorageService> initAsync() async {
  11. _prefs = await SharedPreferences.getInstance();
  12. return SharedStorageService._();
  13. }
  14. ///保存字符串
  15. Future<bool> setString(String key, String value) async {
  16. return await _prefs.setString(key, value);
  17. }
  18. ///保存布尔值
  19. Future<bool> setBool(String key, bool value) async {
  20. return await _prefs.setBool(key, value);
  21. }
  22. ///保存集合
  23. Future<bool> setList(String key, List<String> value) async {
  24. return await _prefs.setStringList(key, value);
  25. }
  26. ///获取缓存的字符串
  27. String? getString(String key) {
  28. return _prefs.getString(key);
  29. }
  30. ///获取缓存的布尔值
  31. bool? getBool(String key) {
  32. return _prefs.getBool(key);
  33. }
  34. ///获取缓存的集合
  35. List<String> getList(String key) {
  36. return _prefs.getStringList(key) ?? [];
  37. }
  38. ///删除缓存
  39. Future<bool> remove(String key) async {
  40. return await _prefs.remove(key);
  41. }
  42. }