在磁碟上儲存鍵值資料
瞭解如何使用 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 靜態方法。傳入一個鍵值對對映,用作初始值。
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),
),
);
}
}