[Flutter]Save data to shared preference in Redux
- M.R

- Aug 19, 2021
- 1 min read
Overview
I'm making a smartphone app with flutter. Redux is used for state management. I want to write the data in the shared preference which I want to keep even if I turn off the app and start it again.
Method
State to save
Save the class below.
class Item{
String name;
int id;
}
class AppState{
List<Item> items;
}2. Add write process to json to each class
class Item{
String name;
int id;
Map toJson()=>{
'name': name,
'id': id as int,
}
}
class AppState{
List<Item> items;
Map toJson()=>{
'items': items,
}
}If a class member contains an instance of another class, that class will call the toJson () method, if any.
3. Added method to write to shared preference
To use sharedpreference, you need to add the following to pubspec.yaml. Please modify the version as appropriate according to the time.
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);Since writing to the shared preference is done asynchronously, make it an async method and wait for the end of writing with await.
4. Add action
Add AddItemAction that add new item.
class AddItemAction{
final Item item;
AddItemAction(this.item);Add the item you want to add to the member variables of that class.
5. Add reducer
Add a reducer to add a new item.
List<Item> ItemsReducer(List<Item> items, action){
if (action is AddItemAction){
return []..addAll(items)
..add(action.item);
}
else{
return items;
}
}6. Add middleware
After adding the item, add the middleware that saves the data in the shared preference.
void AppStateMiddleWare(Store<AppState> store, action, NextDispatcher next) async{
next(action);
if (action is AddItemAction){
saveToPrefs(store.state);
}next (action) adds item. After that, call the method added in 3.
Lastly
I will write how to call from shared preference next time.






Comments