我制作了一个共享首选项文件,用于从应用程序中存储数据。工作不错。但现在我想从存储中删除数据,作为用户的按钮注销。所以,若用户点击注销按钮,数据将从共享的首选项文件中清除。我如何在不同的班级做到这一点?
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
}
这样,您就可以创建和访问该类的单个可重用实例。您可以在类中定义一个可以从外部访问的静态方法。由于static方法只能访问静态数据成员,因此应将sharedPrefernece
成员变量定义为static。以下是如何清除所有数据。
static Future<bool> clearSharedPrefs(){
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.clear();
}
之后,您将能够从任何类调用此方法,就像SharedPreferenceManager.clearSharedPrefs()
一样。
对于数据库、网络和共享偏好相关的任务,遵循singleton模式是一种很好的做法。
这是您应该使用的代码。
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");