検索
[Flutter]Reduxでsharedpreferenceにデータを保存する
- M.R

- 2020年10月3日
- 読了時間: 2分
概要
flutterでスマホアプリを作っている。状態管理にはreduxを使用。アプリを切って再度起動した場合にも保持したいデータをsharedpreferenceに書き込みたい。
やり方
1. 保存する状態
以下のクラスを保存する。
class Item{
String name;
int id;
}
class AppState{
List<Item> items;
}2. 各classにjsonへの書き込み処理を追加する
class Item{
String name;
int id;
Map toJson()=>{
'name': name,
'id': id as int,
}
}
class AppState{
List<Item> items;
Map toJson()=>{
'items': items,
}
}クラスのメンバに別のクラスのインスタンスが含まれる場合は、そのクラスにtoJson()メソッドがあればそれを呼び出してくれる。
3. sharedpreferenceに書き込むメソッドを追加
sharedpreferenceを使用するには、pubspec.yamlに以下を追記する必要がある。バージョンはその時期に応じて適宜修正してください。
dependencies:
・・・
shared_preferences: ^0.4.2import 'package:shared_preferences/shared_preferences.dart';
void saveToPrefs(AppState state) async{
SharedPreferences prefs=await SharedPreferences.getInstance();
var string=json.encode(state.toJson());
await prefs.setString('itemState', string);sharedpreferenceへの書き込みは非同期に行われるので、asyncなメソッドにし、書き込み終了をawaitで待ってあげる。
4. actionを追加
新しいitemを追加するAddItemActionを追加する。
class AddItemAction{
final Item item;
AddItemAction(this.item);追加するitemをメンバ変数として持たせる。
5. reducerを追加
新しいitemを追加するreducerを追加する。
List<Item> ItemsReducer(List<Item> items, action){
if (action is AddItemAction){
return []..addAll(items)
..add(action.item);
}
else{
return items;
}
}6. middlewareを追加
itemを追加した後にsharedpreferenceに保存するmiddlewareを追加する。
void AppStateMiddleWare(Store<AppState> store, action, NextDispatcher next) async{
next(action);
if (action is AddItemAction){
saveToPrefs(store.state);
}next(action)がitemを追加する。その後に3.で追加したメソッドを呼び出す。
終わりに
sharedpreferenceから呼び出す方は次回書きます。






コメント