Flutter之SharedPreferencesUtil初识
一、Android SharedPreferencesUtil工具类
public class SharedPreferencesUtil {
public static final String mTAG = "test";
// 创建一个写入器
private static SharedPreferences mPreferences;
private static SharedPreferences.Editor mEditor;
private static SharedPreferencesUtil mSharedPreferencesUtil;
// 构造方法
public SharedPreferencesUtil(Context context) {
mPreferences = context.getSharedPreferences(mTAG, Context.MODE_PRIVATE);
mEditor = mPreferences.edit();
}
// 单例模式
public static SharedPreferencesUtil getInstance(Context context) {
if (mSharedPreferencesUtil == null) {
mSharedPreferencesUtil = new SharedPreferencesUtil(context);
}
return mSharedPreferencesUtil;
}
// 存入数据
public void putSP(String key, String value) {
mEditor.putString(key, value);
mEditor.commit();
}
// 获取数据
public String getSP(String key) {
return mPreferences.getString(key, "");
}
// 移除数据
public void removeSP(String key) {
mEditor.remove(key);
mEditor.commit();
}
}
在做APP开发时, 会涉及到用户数据的存储(比如保存用户登录token、用户的某些偏好设置等). 开发过Android的朋友应该知道有 SharedPreferences. 在 Flutter 中, 同样为我们提供了十分相似的(甚至名字都一样)组件, 为我们提供数据存储的能力
二、Sharedpreferences 基本用法
存储基本数据类型:
int 类型
onPressed: ()async{
SharedPreferences prefs = await SharedPreferences.getInstance();
int counter = 1;
await prefs.setInt('counter', counter);
},
String类型
await prefs.setString('counter', counter);
bool类型
await prefs.setDouble('counter', counter);
listdata类型
onPressed: ()async{
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String>counter=["1","2"];
await prefs.setStringList('counter', counter);
},
取值基本用法
onPressed: ()async{
SharedPreferences prefs = await SharedPreferences.getInstance();
int counterint =prefs.getInt("counter");
String counter =prefs.getString("counter");
bool counterbool =prefs.getBool("counter");
double counterdouble =prefs.getDouble("counter");
List counterlist =prefs.getStringList("counter");
},
删除指定数据
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key); //删除指定键
清空整个缓存
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear();//清空键值对
三、实例
SharedPreferencesUtil.dart
//utils/shared_preferences_util.dart文件
import 'package:myshop_flutter/config/index.dart';
import 'package:shared_preferences/shared_preferences.dart';
//本地存储工具
class SharedPreferencesUtil {
//token字符串
static String token = "";
//获取token值
static Future getToken() async {
if (token == null || token.isEmpty) {
//从本地取出token值
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
token = sharedPreferences.getString(KString.TOKEN) ?? null;
}
return token;
}
//获取头像url
static Future getImageHead() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.get(KString.HEAD_URL);
}
//获取呢称
static Future getUserName() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
return sharedPreferences.get(KString.NICK_NAME);
}
}
保存用户登录信息