sp_utils.dart 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import 'package:shared_preferences/shared_preferences.dart';
  2. /// 持久化缓存类
  3. ///
  4. /// 使用SharedPreferences共享参数存储
  5. class SPUtils {
  6. SPUtils._();
  7. static SPUtils? _instance;
  8. static SPUtils getInstance() => _instance ??= SPUtils._();
  9. late SharedPreferences _sp;
  10. Future<void> init() async {
  11. _sp = await SharedPreferences.getInstance();
  12. }
  13. /// 获取所有key
  14. Set<String> getKeys() {
  15. return _sp.getKeys();
  16. }
  17. /// 是否有key
  18. bool containsKey(String key) {
  19. return _sp.containsKey(key);
  20. }
  21. /// 以k,v形式 存储各种类型的值
  22. ///
  23. Future<bool> saveString(String key, String value) async {
  24. return await _sp.setString(key, value);
  25. }
  26. Future<bool> saveInt(String key, int value) async {
  27. return await _sp.setInt(key, value);
  28. }
  29. Future<bool> saveDouble(String key, double value) async {
  30. return await _sp.setDouble(key, value);
  31. }
  32. Future<bool> saveBool(String key, bool value) async {
  33. return await _sp.setBool(key, value);
  34. }
  35. Future<bool> saveStringList(String key, List<String> value) async {
  36. return await _sp.setStringList(key, value);
  37. }
  38. /// 获取存储的数据
  39. ///
  40. String? getString(String key) {
  41. return _sp.getString(key);
  42. }
  43. int? getInt(String key) {
  44. return _sp.getInt(key);
  45. }
  46. double? getDouble(String key) {
  47. return _sp.getDouble(key);
  48. }
  49. bool? getBool(String key) {
  50. return _sp.getBool(key);
  51. }
  52. List<String>? getStringList(String key) {
  53. return _sp.getStringList(key);
  54. }
  55. /// 移除存储的数据
  56. ///
  57. Future<bool> remove(String key) async {
  58. return await _sp.remove(key);
  59. }
  60. Future<bool> clear() async {
  61. return await _sp.clear();
  62. }
  63. }