[Flutter]Save data to shared preference in Redux
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.2
import '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.
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