1.shared_preferences库的引入

image.png

2. 缓存管理类HiCache

  1. import 'package:shared_preferences/shared_preferences.dart';
  2. ///缓存管理类
  3. class HiCache {
  4. SharedPreferences prefs;
  5. HiCache._() {
  6. init();
  7. }
  8. static HiCache _instance;
  9. HiCache._pre(SharedPreferences prefs) {
  10. this.prefs = prefs;
  11. }
  12. ///预初始化,防止在使用get时,prefs还未完成初始化
  13. static Future<HiCache> preInit() async {
  14. if (_instance == null) {
  15. var prefs = await SharedPreferences.getInstance();
  16. _instance = HiCache._pre(prefs);
  17. }
  18. return _instance;
  19. }
  20. static HiCache getInstance() {
  21. if (_instance == null) {
  22. _instance = HiCache._();
  23. }
  24. return _instance;
  25. }
  26. void init() async {
  27. if (prefs == null) {
  28. prefs = await SharedPreferences.getInstance();
  29. }
  30. }
  31. setString(String key, String value) {
  32. prefs.setString(key, value);
  33. }
  34. setDouble(String key, double value) {
  35. prefs.setDouble(key, value);
  36. }
  37. setInt(String key, int value) {
  38. prefs.setInt(key, value);
  39. }
  40. setBool(String key, bool value) {
  41. prefs.setBool(key, value);
  42. }
  43. setStringList(String key, List<String> value) {
  44. prefs.setStringList(key, value);
  45. }
  46. T get<T>(String key) {
  47. return prefs.get(key);
  48. }
  49. }

3 初始化

在HomePage的initState中初始化

  1. HiCache.preInit();