git@h5.yoqi.me 1 year ago
parent
commit
56d8fd032b
2 changed files with 51 additions and 3 deletions
  1. 0 3
      lib/utils/sp_util.dart
  2. 51 0
      lib/utils/sp_utils.dart

+ 0 - 3
lib/utils/sp_util.dart

@@ -1,3 +0,0 @@
-class SpUtil{
-  
-}

+ 51 - 0
lib/utils/sp_utils.dart

@@ -0,0 +1,51 @@
+import 'package:shared_preferences/shared_preferences.dart';
+
+class SpUtil {
+  static Future<SharedPreferences> sharedPreferences = SharedPreferences.getInstance();
+
+  static Future<T> get<T>(String key) {
+    key ??= '';
+    return sharedPreferences.then((s) {
+      return s.get(key) as T;
+    });
+  }
+
+  static Future<bool> save<T>(String key, T value) async {
+    key ??= '';
+    return sharedPreferences.then((s) {
+      if (value == null) {
+        return s.remove(key);
+      } else {
+        if (value is int) {
+          return s.setInt(key, value);
+        }
+        if (value is double) {
+          return s.setDouble(key, value);
+        }
+        if (value is String) {
+          return s.setString(key, value);
+        }
+        if (value is List<String>) {
+          return s.setStringList(key, value);
+        }
+        if (value is bool) {
+          return s.setBool(key, value);
+        }
+      }
+      return false;
+    });
+  }
+
+  static Future<bool> remove(String key) {
+    key ??= '';
+    return sharedPreferences.then((s) {
+      return s.remove(key);
+    });
+  }
+
+  static Future<bool> clear() {
+    return sharedPreferences.then((s) {
+      return s.clear();
+    });
+  }
+}