sp_util.dart 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import 'dart:convert';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. class SpUtil {
  4. static Future<SharedPreferences> sharedPreferences =
  5. SharedPreferences.getInstance();
  6. static Future<T> get<T>(String key, T defaultValue) {
  7. return sharedPreferences.then((s) {
  8. if (s.get(key) == null) {
  9. return defaultValue;
  10. } else {
  11. if (defaultValue is int) {
  12. return s.getInt(key) as T;
  13. }
  14. if (defaultValue is double) {
  15. return s.getDouble(key) as T;
  16. }
  17. if (defaultValue is String) {
  18. return s.getString(key) as T;
  19. }
  20. if (defaultValue is List<String>) {
  21. return s.getStringList(key) as T;
  22. }
  23. if (defaultValue is List<Map>) {
  24. List<String>? dataList = s.getStringList(key);
  25. return dataList?.map((value) {
  26. return json.decode(value);
  27. }).toList() as T;
  28. }
  29. if (defaultValue is bool) {
  30. return s.getBool(key) as T;
  31. }
  32. return s.get(key) as T;
  33. }
  34. });
  35. }
  36. static Future<bool> save<T>(String key, T value) async {
  37. return sharedPreferences.then((s) {
  38. if (value == null) {
  39. return s.remove(key);
  40. } else {
  41. if (value is int) {
  42. return s.setInt(key, value);
  43. }
  44. if (value is double) {
  45. return s.setDouble(key, value);
  46. }
  47. if (value is String) {
  48. return s.setString(key, value);
  49. }
  50. if (value is List<String>) {
  51. return s.setStringList(key, value);
  52. }
  53. if (value is List<Map>) {
  54. List<String> dataList = value.map((value) {
  55. return json.encode(value);
  56. }).toList();
  57. return s.setStringList(key, dataList);
  58. }
  59. if (value is bool) {
  60. return s.setBool(key, value);
  61. }
  62. }
  63. return false;
  64. });
  65. }
  66. static Future<bool> remove(String key) {
  67. return sharedPreferences.then((s) {
  68. return s.remove(key);
  69. });
  70. }
  71. static Future<bool> clear() {
  72. return sharedPreferences.then((s) {
  73. return s.clear();
  74. });
  75. }
  76. }