在磁盘上存储键值数据
了解如何使用 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),
),
);
}
}