使用缓存字符串方法报错

来源:3-11 统一缓存管理框架hi_cache设计

YeyuJingming

2021-04-21

我使用 shared_preferences 2.0.5,当我封装完 缓存框架 ,调用 setString的方法传值报错
图片描述

class HiCache {
  SharedPreferences prefs;

  HiCache._() {
    init();
  }

  static HiCache _instance;

  //  获取缓存实例
  static HiCache getInstance() {
    if (_instance == null) {
      _instance = HiCache._();
    }
    return _instance;
  }

  //  预初始化,防止在使用get时,prefs还未完成初始化
  static Future<HiCache> preInit() async {
    if (_instance == null) {
      var prefs = await SharedPreferences.getInstance();
      _instance = HiCache._pre(prefs);
    }
    return _instance;
  }

  void init() async {
    if (prefs == null) {
      prefs = await SharedPreferences.getInstance();
    }
  }

  //  缓存实例预处理
  HiCache._pre(SharedPreferences prefs) {
    this.prefs = prefs;
  }

  setString(String key, String value) {
    prefs.setString(key, value);
  }

  setDouble(String key, double value) {
    prefs.setDouble(key, value);
  }

  setInt(String key, int value) {
    prefs.setInt(key, value);
  }

  setBool(String key, bool value) {
    prefs.setBool(key, value);
  }

  setStringList(String key, List<String> value) {
    prefs.setStringList(key, value);
  }

  //  通过泛型获取 value
  T get<T>(String key) {
    return prefs.get(key);
  }
}

写回答

2回答

CrazyCodeBoy

2021-04-22

报什么错误呢,将错误贴出来我帮你看看,另外也可对照下这块课程源码检查下你的实现看是否有出入的地方呢

0
2
CrazyCodeBoy
回复
YeyuJingming
棒棒哒!
2021-04-23
共2条回复

慕瓜2188959

2021-04-21

贴完整代码吧,打个断点看看getInstance()是不是返回空

0
2
YeyuJingming
但是也用不了
2021-04-21
共2条回复

Flutter高级进阶实战-仿哔哩哔哩-掌握Flutter高阶技能

一次性掌握Flutter高阶技能+商业级复杂项目架构设计与开发方案

1722 学习 · 870 问题

查看课程