android - 如何在颤振中创建 SharedPreferences 的 Singleton 类
问题描述
总是需要的对象,SharedPreferences
但我们使用 await
Like 访问。
await SharedPreferences.getInstance();
这就是为什么我想在 SharedPreferences 中创建 Singleton 类SharedPreferences
并为 GET 和 SET 数据创建静态方法。
但我不知道该怎么做,我尝试但无法成功
请帮助我
解决方案
对于处理单例类,请SharedPreference
遵循 3 个步骤 -
1.把这个类放到你的项目中
import 'dart:async' show Future;
import 'package:shared_preferences/shared_preferences.dart';
class PreferenceUtils {
static Future<SharedPreferences> get _instance async => _prefsInstance ??= await SharedPreferences.getInstance();
static SharedPreferences _prefsInstance;
// call this method from iniState() function of mainApp().
static Future<SharedPreferences> init() async {
_prefsInstance = await _instance;
return _prefsInstance;
}
static String getString(String key, [String defValue]) {
return _prefsInstance.getString(key) ?? defValue ?? "";
}
static Future<bool> setString(String key, String value) async {
var prefs = await _instance;
return prefs?.setString(key, value) ?? Future.value(false);
}
}
2. 从你的主类的 initState() 初始化这个类
PreferenceUtils.init();
3.访问您的方法,例如
PreferenceUtils.setString(AppConstants.USER_NAME, "");
String username = PreferenceUtils.getString(AppConstants.USER_NAME);
推荐阅读
- ruby-on-rails - 数据表(无分页)> 表单提交中缺少参数
- angular - 使用 Microsoft 和 Twitter 登录
- javascript - 如何在 div 标签的下部动态附加 div?
- javascript - webpack 配置文件中的无效主机错误问题?
- python - 根据熊猫中的条件更改数据框的第一行
- machine-learning - Train Accuracy 非常高,Validation 准确率非常高但测试集准确率非常低
- java - 序列化和反序列化具有 ArrayList 字段的类的单例实例的问题
- .net - angular-json-schema-form 不能与 .net Bundleconfig 一起正常工作?
- javascript - 方向服务 Google API,可拖动来源
- sql - 如何在 sql 查询中提取自定义模板?