shared_preferences介紹
shared_preferences主要的作用是用于將數(shù)據(jù)異步持久化到磁盤(pán),因?yàn)槌志没瘮?shù)據(jù)只是存儲(chǔ)到臨時(shí)目錄,當(dāng)app刪除時(shí)該存儲(chǔ)的數(shù)據(jù)就是消失,web開(kāi)發(fā)時(shí)清除瀏覽器存儲(chǔ)的數(shù)據(jù)也將消失。
支持存儲(chǔ)類(lèi)型:
1.bool
2.int
3.double
4.string
5.stringList
shared_preferences應(yīng)用場(chǎng)景
主要用于持久化數(shù)據(jù),如持久化用戶信息、列表數(shù)據(jù)等。
持久化用戶信息
因?yàn)橛脩粜畔⒒臼遣桓淖兊模谝粋€(gè)應(yīng)用程序中常常會(huì)有多個(gè)頁(yè)面需要展示用戶信息,我們不可能每次都去獲取接口,那么本地持久化就會(huì)變得很方便。
持久化列表數(shù)據(jù)
為了給用戶更好的體驗(yàn),在獲取列表數(shù)據(jù)時(shí)我們常常會(huì)先展示舊數(shù)據(jù),帶給用戶更好的體驗(yàn),不至于一打開(kāi)頁(yè)面就是空白的,當(dāng)我們采用持久化列表數(shù)據(jù)后,可以直接先展示本地?cái)?shù)據(jù),當(dāng)網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求回來(lái)后在進(jìn)行數(shù)據(jù)更新。
shared_preferences使用的對(duì)應(yīng)類(lèi)庫(kù)
我們知道每個(gè)平臺(tái)持久化數(shù)據(jù)的方式都不一樣,而shared_preferences針對(duì)不同的平臺(tái)封裝了一個(gè)通用的類(lèi)庫(kù),接下來(lái)我們看看不同平臺(tái)下他們使用的庫(kù)
iOS: NSUserDefaults
Android: SharedPreferences
Web: localStorage
Linux: FileSystem(保存數(shù)據(jù)到本地系統(tǒng)文件庫(kù)中)
Mac OS: FileSystem(保存數(shù)據(jù)到本地系統(tǒng)文件庫(kù)中)
Windows: FileSystem(保存數(shù)據(jù)到本地系統(tǒng)文件庫(kù)中)
shared_preferences基本使用
pubspec.yaml導(dǎo)入依賴
shared_preferences: ^2.0.8
導(dǎo)入頭文件
import 'package:shared_preferences/shared_preferences.dart';
獲取實(shí)例對(duì)象
SharedPreferences? sharedPreferences = await SharedPreferences.getInstance();
設(shè)置持久化數(shù)據(jù)
我們可以通過(guò)sharedPreferences的實(shí)例化對(duì)象調(diào)用對(duì)應(yīng)的set方法設(shè)置持久化數(shù)據(jù)
// 設(shè)置持久化數(shù)據(jù)
void _setData() async {
// 實(shí)例化
sharedPreferences = await SharedPreferences.getInstance();
// 設(shè)置string類(lèi)型
await sharedPreferences?.setString("name", "Jimi");
// 設(shè)置int類(lèi)型
await sharedPreferences?.setInt("age", 18);
// 設(shè)置bool類(lèi)型
await sharedPreferences?.setBool("isTeacher", true);
// 設(shè)置double類(lèi)型
await sharedPreferences?.setDouble("height", 1.88);
// 設(shè)置string類(lèi)型的數(shù)組
await sharedPreferences?.setStringList("action", ["吃飯", "睡覺(jué)", "打豆豆"]);
setState(() {});
}
讀取持久化數(shù)據(jù)
我們可以通過(guò)sharedPreferences的實(shí)例化對(duì)象調(diào)用對(duì)應(yīng)的get方法讀取持久化數(shù)據(jù)
Text("名字: ${sharedPreferences?.getString("name") ?? ""}",
style: TextStyle(
color: Colors.blue,
fontSize: 20
),
),
SizedBox(height: 20,),
Text("年齡: ${sharedPreferences?.getInt("age") ?? ""}",
style: TextStyle(
color: Colors.red,
fontSize: 20
),
),
SizedBox(height: 20,),
Text("是老師嗎?: ${sharedPreferences?.getBool("isTeacher") ?? ""}",
style: TextStyle(
color: Colors.orange,
fontSize: 20
),
),
SizedBox(height: 20,),
Text("身高: ${sharedPreferences?.getDouble("height") ?? ""}",
style: TextStyle(
color: Colors.pink,
fontSize: 20
),
),
SizedBox(height: 20,),
Text("我正在: ${sharedPreferences?.getStringList("action") ?? ""}",
style: TextStyle(
color: Colors.purple,
fontSize: 20
),
),
完整代碼
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPreferencesExample extends StatefulWidget {
@override
_SharedPreferencesExampleState createState() => _SharedPreferencesExampleState();
}
class _SharedPreferencesExampleState extends State<SharedPreferencesExample> {
SharedPreferences? sharedPreferences;
// 設(shè)置持久化數(shù)據(jù)
void _setData() async {
// 實(shí)例化
sharedPreferences = await SharedPreferences.getInstance();
// 設(shè)置string類(lèi)型
await sharedPreferences?.setString("name", "Jimi");
// 設(shè)置int類(lèi)型
await sharedPreferences?.setInt("age", 18);
// 設(shè)置bool類(lèi)型
await sharedPreferences?.setBool("isTeacher", true);
// 設(shè)置double類(lèi)型
await sharedPreferences?.setDouble("height", 1.88);
// 設(shè)置string類(lèi)型的數(shù)組
await sharedPreferences?.setStringList("action", ["吃飯", "睡覺(jué)", "打豆豆"]);
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("SharedPreferences"),
),
floatingActionButton: FloatingActionButton(
onPressed: _setData,
child: Icon(Icons.add),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("名字: ${sharedPreferences?.getString("name") ?? ""}",
style: TextStyle(
color: Colors.blue,
fontSize: 20
),
),
SizedBox(height: 20,),
Text("年齡: ${sharedPreferences?.getInt("age") ?? ""}",
style: TextStyle(
color: Colors.red,
fontSize: 20
),
),
SizedBox(height: 20,),
Text("是老師嗎?: ${sharedPreferences?.getBool("isTeacher") ?? ""}",
style: TextStyle(
color: Colors.orange,
fontSize: 20
),
),
SizedBox(height: 20,),
Text("身高: ${sharedPreferences?.getDouble("height") ?? ""}",
style: TextStyle(
color: Colors.pink,
fontSize: 20
),
),
SizedBox(height: 20,),
Text("我正在: ${sharedPreferences?.getStringList("action") ?? ""}",
style: TextStyle(
color: Colors.purple,
fontSize: 20
),
),
],
),
),
);
}
}
效果如下

shared_preferences輔助操作
獲取持久化數(shù)據(jù)中所有存入的key
List<String> keys = sharedPreferences?.getKeys().toList() ?? [];
print(keys);
// 控制臺(tái)輸出
[name, age, isTeacher, height, action]
判斷持久化數(shù)據(jù)中是否包含某個(gè)key
bool isContainKey = sharedPreferences?.containsKey("name") ?? false;
print(isContainKey);
// 控制臺(tái)輸出
flutter: true
刪除持久化數(shù)據(jù)中某個(gè)key
bool isRemoveKey = await sharedPreferences?.remove("name") ?? false;
print(isRemoveKey);
// 控制臺(tái)輸出
flutter: true
清除所有持久化數(shù)據(jù)
bool isClearAllKey = await sharedPreferences?.clear() ?? false;
print(isClearAllKey);
// 控制臺(tái)輸出
flutter: true
重新加載所有數(shù)據(jù)(僅重載運(yùn)行時(shí))
await sharedPreferences?.reload();
本篇主要講shared_preferences的使用,下篇就來(lái)講講shared_preferences的源碼和封裝。