Study of thereduxThe purpose of

Create our data management file

Recently, I learned about Flutter. Since the previous technology stack was mainly VUE, when I approached Flutter, my first concern was how the data would flow globally. In the previous vUE we had vuex, in React we had Redux, and we also had localstorage. So what should we do with Flutter? I have found a lot of articles on the Internet, all of which are some very patchwork things, so I am going to try to write an article for reference.

The old rule is to install the package first
Dependencies: Flutter_redux: ^0.5.3Copy the code
To establish aapp_state.dartFiles, we define three types

Count is an int, user is a JS object, and demo is an array

class AppState{
  int count;
  User user;
  List<DemoList> demo;
  
  AppState({
    this.count,
    this.user,
    this.demo
  });
}
Copy the code
Define the User object and the Demo array
class User{ int id; String name; User({ this.id, this.name }); } class DemoList{ String id; String name; String age; String job; DemoList({ this.id, this.name, this.age, this.job }); DemoList.fromJSON(Map<String, dynamic> json){ id = json['id']?.toString(); name = json['name']? .toString(); age = json['age']? .toString(); job = json['job']? .toString(); } Map<String,dynamic>toJson(){ final Map<String,dynamic> data = <String,dynamic>{}; data['id'] = id; data['name'] = name; data['age'] = age; data['job'] = job; return data; }}Copy the code

We can serialize the demoList manually, but plugins can also serialize it. For serialization, see my other article juejin.cn/post/696656…

Let’s define the initial values of count, User,demo in AppState
  static AppState initialState(){
    return AppState(
      count: 0, 
      user: new User(id: 1,name:'zwm'),
      demo: [
        DemoList(
          id:'1',
          name:'1',
          age:'1',
          job:'1'
        ),
        DemoList(
          id:'2',
          name:'2',
          age:'2',
          job:'2'
        ),
      ] 
    );
  }
Copy the code
AppState defines a function
  AppState copyWith ({count,user,demo}){
    return AppState(
      count: count ?? this.count,
      user: user ?? this.user,
      demo: demo ?? this.demo
    );
  }
Copy the code
Define an action to operate on the defined array
// IncrementAction {final payload; IncrementAction({this.payload}); } // object class GetUserAction{final payload; GetUserAction({this.payload}); } // Array class AddDemoListAction{final payload; AddDemoListAction({this.payload}); }Copy the code
Define the reducer
AppState appReducer(AppState state, dynamic action) { switch (action.runtimeType) { case IncrementAction: return state.copyWith(count: state.count + action.payload); case GetUserAction: return state.copyWith(user:User(id:action.payload.id,name:action.payload.name)); case AddDemoListAction: for (int i = 0; i < action.payload.length; i++) { state.demo.add(action.payload[i]); } return state; default: return state; }}Copy the code
app_state.dartFile code
class AppState{ int count; User user; List<DemoList> demo; AppState({ this.count, this.user, this.demo }); static AppState initialState(){ return AppState( count: 0, user: new User(id: 1,name:'zwm'), demo: [ DemoList( id:'1', name:'1', age:'1', job:'1' ), DemoList( id:'2', name:'2', age:'2', job:'2' ), ] ); } AppState copyWith ({count,user,demo}){ return AppState( count: count ?? this.count, user: user ?? this.user, demo: demo ?? this.demo ); } } class User{ int id; String name; User({ this.id, this.name }); } class IncrementAction { final payload; IncrementAction({this.payload}); } class GetUserAction{ final payload; GetUserAction({this.payload}); } class AddDemoListAction{ final payload; AddDemoListAction({this.payload}); } class DemoList{ String id; String name; String age; String job; DemoList({ this.id, this.name, this.age, this.job }); DemoList.fromJSON(Map<String, dynamic> json){ id = json['id']?.toString(); name = json['name']? .toString(); age = json['age']? .toString(); job = json['job']? .toString(); } Map<String,dynamic>toJson(){ final Map<String,dynamic> data = <String,dynamic>{}; data['id'] = id; data['name'] = name; data['age'] = age; data['job'] = job; return data; } } AppState appReducer(AppState state, dynamic action) { switch (action.runtimeType) { case IncrementAction: return state.copyWith(count: state.count + action.payload); case GetUserAction: return state.copyWith(user:User(id:action.payload.id,name:action.payload.name)); case AddDemoListAction: for (int i = 0; i < action.payload.length; i++) { state.demo.add(action.payload[i]); } return state; default: return state; }}Copy the code

React buckets react buckets React buckets React buckets React buckets

Go to the list to use the action

Class MyApp extends StatelessWidget {// Define our store, AppReducer and initialState methods final store = Store<AppState>(appReducer, initialState: AppState.initialState()); @override Widget build(BuildContext context) {return StoreProvider(store: store, child: MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), routes: : (context) = {"/" > MyHomePage (), / / registration page routing},)); }}Copy the code
The value of count is displayed in the operation
body: Container( child: new Column( children: <Widget>[ StoreConnector<AppState, String>( builder: (context, value) { return Text(value, style: Theme.of(context).textTheme.display1); }, converter: (Store store) { return store.state.count.toString(); } ) ], ) ), floatingActionButton: StoreConnector<AppState, VoidCallback>( converter: (Store Store) {// a small +1 logic return () => Store. Dispatch (IncrementAction(payload: 1)); }, builder: (BuildContext context, VoidCallback callback) { return FloatingActionButton( onPressed: callback, child: Icon(Icons.add)); },),Copy the code
Display and operation of the User object
StoreConnector<AppState, User>(Builder: (context, User) {return Text(user.name,); }, Converter: (store) => store.state.user), logic StoreConnector<AppState, VoidCallback>(Converter: (Store Store) {return () => Store. Dispatch (GetUserAction(payload: User(id:1,name:' I'm Sam '))); }, Builder: (BuildContext Context, VoidCallback callback) {return FloatingActionButton(onPressed: callback, child: Icon(Icons.add)); },),Copy the code
The demo array is displayed in the operation
// Display StoreConnector<AppState, List<DemoList>>(Converter: (store) => store.state.demo, Builder: (BuildContext Context, demo){return new Container(height: 500.0, child: ListView.builder(itemCount: itemCount) demo.length, itemBuilder: (BuildContext context, int position){ return new Padding( padding: EdgeInsets. All (10.0), child: new Row(children: <Widget>[new Text(demo[position].name),],); },),); },), // Call StoreConnector<AppState, VoidCallback>(Converter: (Store store) { return () => store.dispatch(AddDemoListAction(payload:this.demodemo)); }, builder: (BuildContext context, VoidCallback callback) { return FloatingActionButton( onPressed: callback, child: Icon(Icons.add)); },),Copy the code

This is how simple data flows

Because it is just learning, a lot of bad places I hope you can point out, thank you 🙏