shared_preferences是Flutter推薦使用的一個本地數(shù)據(jù)存取插件
1.簡單的,異步的,持久化的key-value存儲系統(tǒng)
2.在Android上它是基于[SharedPreferences]的
3.在iOS上它是基于[NSUserDefaults]
使用方法:(根據(jù)使用文檔)
1.在pubspec.yaml中添加依賴,shared_preferences: ^0.5.4,執(zhí)行Pakagets get進行安裝
2.導入import 'package:shared_preferences/shared_preferences.dart'
3.初始化 SharedPreferences prefs = await SharedPreferences.getInstance();
4.支持[int], [double], [bool], [string] 與 [stringList]類型的數(shù)據(jù)存儲,存值 :
await prefs.setInt('counter', counter);
5.取值:
int counter = (prefs.getInt('counter') ?? 0) + 1;
項目代碼:
/*登錄用戶數(shù)據(jù)緩存*/
static User get currentUser {
Map user = convert.jsonDecode(prefs.getString('login_user'));
return User.fromJson(user);
}
static saveUserInfo(Map user) {
String jsonStr = convert.jsonEncode(user);
prefs.setString('login_user', jsonStr);
print('Save Complete');
}