存储键值对数据

如果你要存储的键值集合相对较少,则可以用 shared_preferences 插件。

通常你需要在两个平台用原生的方式存储数据。幸运的是 shared_preferences 插件可以把 key-value 保存到磁盘中。

这个教程包含以下步骤:

  1. 添加依赖

  2. 保存数据

  3. 读取数据

  4. 移除数据

1. 添加依赖

在开始之前,你需要添加 shared_preferences 为依赖:

运行 flutter pub addshared_preferences 添加为依赖:

flutter pub add shared_preferences

2. 保存数据

要存储数据,请使用 SharedPreferences 类的 setter 方法。 Setter方法可用于各种基本数据类型,例如 setIntsetBoolsetString

Setter 方法做两件事:首先,同步更新 key-value 到内存中,然后保存到磁盘中。

// 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 方法。

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;

Note that the getter methods throw an exception if the persisted value has a different type than the getter method expects.

4. 移除数据

使用 remove() 方法删除数据。

final prefs = await SharedPreferences.getInstance();

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

支持类型

虽然使用 shared_preferences 提供的键值对存储非常简单方便,但是它也有以下局限性:

  • 只能用于基本数据类型: intdoubleboolstringList<String>

  • 不是为存储大量数据而设计的。

  • 不能确保应用重启后数据仍然存在。

测试支持

使用 shared_preferences 来存储测试代码的数据是一个不错的思路。为此,你需要使用 package 自带的基于内存的模拟持久化存储。

在你的测试中,你可以通过在测试文件的 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),
      ),
    );
  }
}