2021/4/1 Flutter : Store key-value data on diskの訳

Contents

Store key-value data on disk

保存するキーバリューペアのコレクションが比較的少ない場合は、shared_preferencesプラグインを使用できます。

通常、iOSとAndroidの両方にデータを保存するには、ネイティブプラットフォーム統合を作成する必要があります。

幸い、shared_preferencesプラグインを使用して、Key-Valueデータをディスク(デバイス)に永続化できます。

shared_preferencesプラグインはiOSのNSUserDefaultsとAndroidのSharedPreferencesをラップしたもので、単純なデータの永続的なストア(保存機能)を提供します。

このレシピでは、次の手順を使用します。

  1. Add the dependency.
  2. Save data.
  3. Read data.
  4. Remove data.

1. Add the dependency

開始する前に、shared_preferences プラグインをpubspec.yamlファイルに追加ます。

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "<newest version>"

 


2. Save data

データを永続化するには、SharedPreferencesクラスが提供するsetterメソッドを使用し ます。

setInt,setBool,setStringなど、setterメソッドはプリミティブ型で使用できます。

セッターメソッドは2つのことを行います。1つは、メモリ内のキーと値のペアを同期的に更新することです。次に、データをディスクに永続化します。

// obtain shared preferences
final prefs = await SharedPreferences.getInstance();

// set value
prefs.setInt('counter', counter);

 


3. Read data

データを読み取るには、SharedPreferencesクラスが提供する適切なgetterメソッドを使用します 。

getInt ⇄ setInt

getBool ⇄ setBool

getString ⇄ setString

のようにセッターごとに、対応するゲッターがあります。


4. Remove data

データを削除するには、このremove()メソッドを使用します。

final prefs = await SharedPreferences.getInstance();

prefs.remove('counter');


Supported types

Key-Valueストレージは使いやすく便利ですが、次のような制限があります。

  • プリミティブ型のみ使用できます。int型,double型,bool型,string,型そしてstringList型です。
  • 大量のデータを保存するようには設計されていません。

Testing support

shared_preferencesを使用してデータを永続化するコードをテストすることをお勧めします

shared_preferencesライブラリで使用されているMethodChannelをモックアウトすることで実行できます

工事中🏗


Complete example

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of the application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Shared preferences demo',
      home: MyHomePage(title: 'Shared preferences demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _loadCounter();
  }

  //Loading counter value on start
  void _loadCounter() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt('counter') ?? 0);
    });
  }

  //Incrementing counter after click
  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.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

 

 

参考

https://flutter.dev/docs/cookbook/persistence/key-value

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です