StoreHelper.dart 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import 'package:shared_preferences/shared_preferences.dart';
  2. import 'package:synchronized/synchronized.dart';
  3. class StoreHelper {
  4. static StoreHelper? _instance;
  5. static late SharedPreferences prefs;
  6. static final Lock _lock = Lock();
  7. static Future<StoreHelper?> init() async {
  8. if (_instance == null) {
  9. print("SpHelper初始化中");
  10. await _lock.synchronized(() async {
  11. // 保持本地实例直到完全初始化。
  12. var singleton = StoreHelper();
  13. await singleton._init();
  14. _instance = singleton;
  15. });
  16. }
  17. print("SpHelper初始化完成");
  18. return _instance;
  19. }
  20. Future _init() async {
  21. prefs = await SharedPreferences.getInstance();
  22. }
  23. static void putStorage(String key, value) async {
  24. if (value is String) {
  25. prefs.setString(key, value);
  26. } else if (value is num) {
  27. prefs.setInt(key, value as int);
  28. } else if (value is double) {
  29. prefs.setDouble(key, value);
  30. } else if (value is bool) {
  31. prefs.setBool(key, value);
  32. } else if (value is List) {
  33. prefs.setStringList(key, value.cast<String>());
  34. }
  35. }
  36. // 获取
  37. static getStorage(String key, [dynamic replace]) {
  38. if (prefs == null) return;
  39. return prefs.get(key) ?? replace;
  40. }
  41. // 移除
  42. static removeStorage(String key) {
  43. if (prefs == null) return;
  44. prefs.remove(key);
  45. }
  46. static removeAllStorage() {
  47. if (prefs == null) return;
  48. prefs.clear();
  49. }
  50. }