Contents
Store key-value data on disk
保存するキーバリューペアのコレクションが比較的少ない場合は、shared_preferences
プラグインを使用できます。
通常、iOSとAndroidの両方にデータを保存するには、ネイティブプラットフォーム統合を作成する必要があります。
幸い、shared_preferences
プラグインを使用して、Key-Valueデータをディスク(デバイス)に永続化できます。
shared_preferences
プラグインはiOSのNSUserDefaultsとAndroidのSharedPreferencesをラップしたもので、単純なデータの永続的なストア(保存機能)を提供します。
このレシピでは、次の手順を使用します。
- Add the dependency.
- Save data.
- Read data.
- 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. ); } }
参考