在磁碟上儲存鍵值資料
如果您有相對少量要儲存的鍵值對,可以使用 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),
),
);
}
}
除非另有說明,否則本網站上的文件反映了 Flutter 的最新穩定版本。頁面最後更新於 2024-07-06。 檢視原始碼 或 回報問題。