总是SharedPreferences
的必需对象,但我们使用await
Like访问。
await SharedPreferences.getInstance();
这就是为什么我想创建SharedPreferences
的Singleton类并为SharedPreferences中的GET&SET数据创建静态方法的原因。
但是我不知道该怎么做,我尝试但无法成功请帮助我
这是我的偏好解决方案:
class Storage {
static const String _some_field = 'some_field';
static Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
static Future<String> getSomeStringData() async =>
(await prefs).getString(_some_field) ?? '';
static Future setSomeStringData(String phone) async =>
(await prefs).setString(_some_field, phone);
static Future clear() async {
await getSomeStringData(null);
}
}
我将此代码用于单例设置
static Future<SharedPreferences> getInstance() async
{
SharedPreferences preferences ;
preferences = await SharedPreferences.getInstance();
return preferences;
}
然后使用它来还原您的数据,这里我还原userId。
/// ----------------------------------------------------------
/// Method that saves/restores the userId
/// ----------------------------------------------------------
static Future<String> getUserId() async {
return getInstance().then((pref) {
return pref.get(Constants.userId);
});
}
希望有帮助:)
class YourClass {
static final YourClass _singleton =
new YourClass._internal();
factory YourClass(){
return _singleton;
}
YourClass._internal(){
//initialization your logic here
}
}
//主代码环境
YourClass mClass = new YourClass(); //将单身人士找回来
对于句柄单例类SharedPreference
,请遵循以下3个步骤-
import 'dart:async' show Future;
import 'package:shared_preferences/shared_preferences.dart';
class PreferenceUtils {
static Future<SharedPreferences> get _instance async => _prefs ??= await SharedPreferences.getInstance();
static SharedPreferences _prefs;
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);
}
}
PreferenceUtils.init();
PreferenceUtils.setString(AppConstants.USER_NAME, "");
String username = PreferenceUtils.getString(AppConstants.USER_NAME);