[Flutter]Read data from shared preference in Redux
Overview
I'm making a smartphone app with flutter. Redux is used for state management. Save the data I want to keep even if the application is turn off in the shared preference. Since I wrote about writing last time, this time I will summarize about reading.
Method
1. State to save
The saved data is as follows.
class Item{
String name;
int id;
}
class AppState{
List<Item> items;
}
2. Create a constructor to read from json in each class
Item.fromJson(Map json){
id=json['id'] as int;
name=json['name'];
}
AppState.fromJson(Map json){
items=(json['items'] as List).map((m)=> Item.fromJson(m)).toList()
}
If the member contains a class instance, the fromJson () constructor should be prepared for that class as in the case of writing.
3. Add method to read from shared preference
Future<AppState> loadFromPrefs() async{
SharedPreferences prefs=await SharedPreferences.getInstance();
var string=prefs.getString('itemState');
if (string!=null){
Map map=json.decode(string);
return AppState.fromJson(map);
}
return AppState.InitState();
}
Read the data asynchronously and wait for the end with await.
4. Add action
Add LoadItemAction to read data from shared preference to store and GetItemAction to read data from store.
class LoadItemAction{
final List<Item> items;
LoadItemAction(this.items);
}
class GetItemAction{}
In LoadItemAction, the data brought from the shared preference to be saved in the store is taken as an argument. GetItemAction only retrieves store data, so there are no arguments.
5. Add reducer
List<Item> ItemsReducer(List<Item> items, action){
if (action is GetItemAction){
return items;
}
if (action is LoadItemAction){
return action.items;
}
}
LoadItemAction returns the data passed as an argument, and GetItemAction returns the data retrieved from the store as it is.
6. Add middleware
Add the method read from the shared preference to middleware.
void AppStateMiddleWare(Store<AppState> store, action, NextDispatcher next) async{
if (action is GetItemAction){
await loadFromPrefs()
.then((state) =>
store.dispatch(LoadItemAction(state.items)));
}
next(action);
}
Wait for loading from shared preference with await, and when completed, pass it to the argument of LoadItemAction and save it in store. After that, it is called from store by GetItemAction (next (action)).
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Comments