使用缓存字符串方法报错
来源: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
报什么错误呢,将错误贴出来我帮你看看,另外也可对照下这块课程源码检查下你的实现看是否有出入的地方呢
022021-04-23 -
慕瓜2188959
2021-04-21
贴完整代码吧,打个断点看看getInstance()是不是返回空
022021-04-21
相似问题