How to create Singleton class of SharedPreferences in flutter(如何在颤振中创建 SharedPreferences 的 Singleton 类)
问题描述
SharedPreferences
始终是必需的对象,但我们使用 await
Like 访问.
Always required object of SharedPreferences
but we access using await
Like.
等待 SharedPreferences.getInstance();
这就是为什么我想创建 SharedPreferences
的 Singleton 类并为 GET & 创建静态方法的原因在 SharedPreferences 中设置数据.
That's why I thought create Singleton class of SharedPreferences
and create static method for GET & SET data in SharedPreferences.
但我不知道该怎么做,我尝试但无法成功
请帮帮我
But I dont know how to do this, I try but cant get success
Please Help me
推荐答案
处理单例类 SharedPreference
有 3 个步骤-
For handle singleton class SharedPreference
follow there 3 steps
-
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);
这篇关于如何在颤振中创建 SharedPreferences 的 Singleton 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在颤振中创建 SharedPreferences 的 Singleton 类


基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01