如果你需要保存相对少量键值对数据,可以使用 shared_preferences 插件。

通常,你需要在每个平台上编写原生平台集成代码来存储数据。幸运的是,shared_preferences 插件可以用于将键值数据持久化到 Flutter 支持的每个平台的磁盘上。

本示例将采取以下步骤

  1. 添加依赖。
  2. 保存数据。
  3. 读取数据。
  4. 移除数据。

1. 添加依赖

#

开始之前,请将 shared_preferences 软件包添加为依赖。

要将 shared_preferences 软件包添加为依赖,运行 flutter pub add

flutter pub add shared_preferences

2. 保存数据

#

要持久化数据,请使用 SharedPreferences 类提供的 setter 方法。Setter 方法适用于各种原始类型,例如 setIntsetBoolsetString

Setter 方法执行两项操作:首先,同步更新内存中的键值对。然后,将数据持久化到磁盘。

dart
// 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。例如,你可以使用 getIntgetBoolgetString 方法。

dart
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() 方法。

dart
final prefs = await SharedPreferences.getInstance();

// Remove the counter key-value pair from persistent storage.
await prefs.remove('counter');

支持的类型

#

尽管 shared_preferences 提供的键值存储简单方便易用,但它存在局限性

  • 只能使用原始类型:intdoubleboolStringList<String>
  • 它不适用于存储大量数据。
  • 无法保证数据在应用重启后依然持久化。

测试支持

#

测试使用 shared_preferences 持久化数据的代码是个好主意。为此,该软件包提供了偏好设置存储的内存中模拟实现。

要设置你的测试以使用模拟实现,请在测试文件的 setUpAll() 方法中调用 setMockInitialValues 静态方法。传入一个键值对的映射作为初始值。

dart
SharedPreferences.setMockInitialValues(<String, Object>{'counter': 2});

完整示例

#
dart
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),
      ),
    );
  }
}