儲存鍵值對資料

如果你要儲存的鍵值集合相對較少,則可以用 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),
      ),
    );
  }
}