preference_utils.dart 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import 'package:shared_preferences/shared_preferences.dart';
  2. import 'dart:async';
  3. /// shared_preferences 管理类
  4. class PreferenceUtils {
  5. static PreferenceUtils _instance;
  6. static PreferenceUtils get instance => PreferenceUtils();
  7. PreferenceUtils._internal();
  8. factory PreferenceUtils() {
  9. if (_instance == null) _instance = PreferenceUtils._internal();
  10. return _instance;
  11. }
  12. saveInteger(String key, int value) => SharedPreferences.getInstance().then((sp) => sp.setInt(key, value));
  13. saveString(String key, String value) => SharedPreferences.getInstance().then((sp) => sp.setString(key, value));
  14. saveBool(String key, bool value) => SharedPreferences.getInstance().then((sp) => sp.setBool(key, value));
  15. saveDouble(String key, double value) => SharedPreferences.getInstance().then((sp) => sp.setDouble(key, value));
  16. saveStringList(String key, List<String> value) => SharedPreferences.getInstance().then((sp) => sp.setStringList(key, value));
  17. Future<int> getInteger(String key, [int defaultValue = 0]) async {
  18. var sp = await SharedPreferences.getInstance();
  19. var value = sp.getInt(key);
  20. return value ?? defaultValue;
  21. }
  22. Future<String> getString(String key, [String defaultValue = '']) async {
  23. var sp = await SharedPreferences.getInstance();
  24. var value = sp.getString(key);
  25. return value ?? defaultValue;
  26. }
  27. Future<bool> getBool(String key, [bool defaultValue = false]) async {
  28. var sp = await SharedPreferences.getInstance();
  29. var value = sp.getBool(key);
  30. return value ?? defaultValue;
  31. }
  32. Future<double> getDouble(String key, [double defaultValue = 0.0]) async {
  33. var sp = await SharedPreferences.getInstance();
  34. var value = sp.getDouble(key);
  35. return value ?? defaultValue;
  36. }
  37. Future<List<String>> getStringList(String key, [List<String> defaultValue = const <String>[]]) async {
  38. var sp = await SharedPreferences.getInstance();
  39. var value = sp.getStringList(key);
  40. return value ?? defaultValue;
  41. }
  42. }