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