flutter使用shared_preferences进行缓存管理
第一步:在pub.dev中获取shared_preferences
第二步:在页面中导入shared_preferences
第三步:定义缓存类:
class HiCache {
SharedPreferences prefs;
HiCache._() {
init();
}
static HiCache _instance;
HiCache._pre(SharedPreferences prefs) {
this.prefs = prefs;
}
/// 预初始化,防止在get使用时,sharedPreference还未初始化
static Future<HiCache> preInstance() async {
if (_instance == null) {
var prefs = await SharedPreferences.getInstance();
_instance = HiCache._pre(prefs);
}
return _instance;
}
static HiCache getInstance() {
if (_instance == null) {
_instance = HiCache._();
}
return _instance;
}
void init() async {
if (prefs == null) {
prefs = await SharedPreferences.getInstance();
}
}
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);
}
T get<T>(String key) {
return prefs?.get(key) ?? null;
}
}
第四步:使用cache
String username = await HiCache.getInstance().get('userName');