如何解决如何在flutter中从单例中删除共享首选项的数据?
我将一个文件设为共享首选项,以将数据存储在我的应用程序中。一切正常。但是现在我想从存储中删除数据作为用户的按钮注销。因此,如果用户单击注销数据的按钮将从共享首选项文件中清除。我该如何从不同的班级做呢?
import 'package:shared_preferences/shared_preferences.dart';
class MyPreferences{
static const USER = "user";
static const PASSWORD = "password";
static final MyPreferences instance = MyPreferences._internal();
//Campos a manejar
SharedPreferences _sharedPreferences;
String user = "";
String password = "";
MyPreferences._internal(){
}
factory MyPreferences()=>instance;
Future<SharedPreferences> get preferences async{
if(_sharedPreferences != null){
return _sharedPreferences;
}else{
_sharedPreferences = await SharedPreferences.getInstance();
user = _sharedPreferences.getString(USER);
password = _sharedPreferences.getString(PASSWORD);
return _sharedPreferences;
}
}
Future<bool> commit() async {
await _sharedPreferences.setString(USER,user);
await _sharedPreferences.setString(PASSWORD,password);
}
Future<MyPreferences> init() async{
_sharedPreferences = await preferences;
return this;
}
}
解决方法
按照给定的singleton
定义共享首选项管理器类,
class SharedPreferenceManager{
static final SharedPreferenceManager _singleton = new SharedPreferenceManager._internal();
factory SharedPreferenceManager() {
return _singleton;
}
SharedPreferenceManager._internal() {
... // initialization logic here
}
... // rest of the class
}
这样,您可以创建和访问该类的单个可重用实例。您可以在类中定义一个可以从外部访问的静态方法。由于静态方法只能访问静态数据成员,因此应将sharedPrefernece
成员变量定义为静态。这是清除所有数据的方法。
static Future<bool> clearSharedPrefs(){
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.clear();
}
此后,您将可以从任何类调用此方法,就像SharedPreferenceManager.clearSharedPrefs()
一样。
对于数据库,网络和共享首选项相关任务,遵循单例模式是一个好习惯。
这是您应该使用的代码。
import 'package:shared_preferences/shared_preferences.dart';
class MyPreferences{
static const USER = "user";
static const PASSWORD = "password";
static final MyPreferences instance = MyPreferences._internal();
static SharedPreferences _sharedPreferences;
String user = "";
String password = "";
MyPreferences._internal(){}
factory MyPreferences()=>instance;
Future<SharedPreferences> get preferences async{
if(_sharedPreferences != null){
return _sharedPreferences;
}else{
_sharedPreferences = await SharedPreferences.getInstance();
user = _sharedPreferences.getString(USER);
password = _sharedPreferences.getString(PASSWORD);
return _sharedPreferences;
}
}
Future<bool> commit() async {
await _sharedPreferences.setString(USER,user);
await _sharedPreferences.setString(PASSWORD,password);
}
Future<MyPreferences> init() async{
_sharedPreferences = await preferences;
return this;
}
static Future<bool> clearPreference() async{
if(_sharedPreferences){
_sharedPreferences.clear();
}
}
}
,
您可以在共享的首选项上使用remove
或clear
。
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.clear();
// OR
preferences.remove("MY KEY HERE");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。