| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- import 'package:shared_preferences/shared_preferences.dart';
- import 'package:synchronized/synchronized.dart';
- class StoreHelper {
- static StoreHelper? _instance;
- static late SharedPreferences prefs;
- static final Lock _lock = Lock();
- static Future<StoreHelper?> init() async {
- if (_instance == null) {
- print("SpHelper初始化中");
- await _lock.synchronized(() async {
- // 保持本地实例直到完全初始化。
- var singleton = StoreHelper();
- await singleton._init();
- _instance = singleton;
- });
- }
- print("SpHelper初始化完成");
- return _instance;
- }
- Future _init() async {
- prefs = await SharedPreferences.getInstance();
- }
- static void putStorage(String key, value) async {
- if (value is String) {
- prefs.setString(key, value);
- } else if (value is num) {
- prefs.setInt(key, value as int);
- } else if (value is double) {
- prefs.setDouble(key, value);
- } else if (value is bool) {
- prefs.setBool(key, value);
- } else if (value is List) {
- prefs.setStringList(key, value.cast<String>());
- }
- }
- // 获取
- static getStorage(String key, [dynamic replace]) {
- if (prefs == null) return;
- return prefs.get(key) ?? replace;
- }
- // 移除
- static removeStorage(String key) {
- if (prefs == null) return;
- prefs.remove(key);
- }
- static removeAllStorage() {
- if (prefs == null) return;
- prefs.clear();
- }
- }
|