在磁碟上儲存鍵值資料
瞭解如何使用 shared_preferences 包來儲存鍵值對資料。
如果你需要儲存的鍵值對集合較小,可以使用 shared_preferences 外掛。
通常情況下,你必須為每個平臺編寫原生平臺整合程式碼來儲存資料。幸運的是,shared_preferences 外掛可以用於在 Flutter 支援的每個平臺上將鍵值對資料持久化到磁碟。
本示例將採取以下步驟
- 新增依賴。
- 儲存資料。
- 讀取資料。
- 移除資料。
1. 新增依賴
#開始之前,請新增 shared_preferences 包作為依賴。
要將 shared_preferences 包新增為依賴,請執行 flutter pub add
flutter pub add shared_preferences
2. 儲存資料
#要持久化資料,請使用 SharedPreferences 類提供的 setter 方法。Setter 方法適用於各種基本型別,例如 setInt、setBool 和 setString。
Setter 方法執行兩項操作:首先,同步更新記憶體中的鍵值對。然後,將資料持久化到磁碟。
// Load and obtain the shared preferences for this app.
final prefs = await SharedPreferences.getInstance();
// Save the counter value to persistent storage under the 'counter' key.
await prefs.setInt('counter', counter);
3. 讀取資料
#要讀取資料,請使用 SharedPreferences 類提供的相應 getter 方法。每個 setter 都有一個對應的 getter。例如,你可以使用 getInt、getBool 和 getString 方法。
final prefs = await SharedPreferences.getInstance();
// Try reading the counter value from persistent storage.
// If not present, null is returned, so default to 0.
final counter = prefs.getInt('counter') ?? 0;
請注意,如果持久化值的型別與 getter 方法預期的型別不同,getter 方法會丟擲異常。
4. 移除資料
#要刪除資料,請使用 remove() 方法。
final prefs = await SharedPreferences.getInstance();
// Remove the counter key-value pair from persistent storage.
await prefs.remove('counter');
支援的型別
#雖然 shared_preferences 提供的鍵值儲存簡單易用,但它有一些侷限性:
- 只能使用基本型別:
int、double、bool、String和List<String>。 - 它不適合儲存大量資料。
- 無法保證資料在應用重啟後一定會被持久化。
測試支援
#測試使用 shared_preferences 持久化資料的程式碼是一個好習慣。為了實現這一點,該包提供了一個記憶體中的偏好設定儲存模擬實現。
要設定測試以使用模擬實現,請在測試檔案的 setUpAll() 方法中呼叫 setMockInitialValues 靜態方法。傳入一個包含鍵值對的 map 作為初始值。
SharedPreferences.setMockInitialValues(<String, Object>{'counter': 2});
完整示例
#import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Shared preferences demo',
home: MyHomePage(title: 'Shared preferences demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
@override
void initState() {
super.initState();
_loadCounter();
}
/// Load the initial counter value from persistent storage on start,
/// or fallback to 0 if it doesn't exist.
Future<void> _loadCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = prefs.getInt('counter') ?? 0;
});
}
/// After a click, increment the counter state and
/// asynchronously save it to persistent storage.
Future<void> _incrementCounter() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0) + 1;
prefs.setInt('counter', _counter);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('You have pushed the button this many times: '),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}