如何在Flutter中简单的使用redux

365 阅读3分钟

学习的redux的初衷

创建我们的数据管理文件

最近在学习Flutter,由于以前技术栈主要是vue,接触flutter时,我首先考虑到的是数据怎么在全局中流通呢?在之前的vue中,我们有vuex,react中有redux,而且我们还有localstorage。那么在flutter中,我们应该做呢?我自己在网上找了很多的文章,全部都是一些很拼拼凑凑的东西,所以我自己准备尝试写一篇文章以供参考。

老规矩先安装文件包
dependencies:
  flutter:
    sdk: flutter
    
  flutter_redux: ^0.5.3
建立一个app_state.dart文件,我们定义三种类型

count是一个int类型,user对应js中的对象,demo对应数组

class AppState{
  int count;
  User user;
  List<DemoList> demo;
  
  AppState({
    this.count,
    this.user,
    this.demo
  });
}
定义User对象和demo数组
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;
  }      
}

这里我们对demoList进行了手动序列化,当然插件序列化也可以,关于序列化的问题,可以看我另外一篇文章 juejin.cn/post/696656…

AppState里面定义一下count,User,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中定义个一个function
  AppState copyWith ({count,user,demo}){
    return AppState(
      count: count ?? this.count,
      user: user ?? this.user,
      demo: demo ?? this.demo
    );
  }
定义action,对定义的数组进行操作
//数字
class IncrementAction {
  final payload;
  IncrementAction({this.payload});
}
//对象
class GetUserAction{
  final payload;
  GetUserAction({this.payload});
}
//数组
class AddDemoListAction{
  final payload;
  AddDemoListAction({this.payload});
}

定义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;
  }
}
app_state.dart文件代码
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;
  }

}

到了这里,我们前端的朋友肯定都看懂了,这就是一个react全家桶的简单用法。

去列表中去使用操作


class MyApp extends StatelessWidget {
    //先定义我们的store,appReducer和initialState方法在我们的app_state.dart文件中
  final store = Store<AppState>(appReducer, initialState: AppState.initialState());
  
  @override
  Widget build(BuildContext context) {
  //StoreProvider 方法别弄丢了
    return StoreProvider(
      store: store, 
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        routes: {
          "/":(context) => MyHomePage(), //注册首页路由
        },
      )
    );
  }
}
count值的展示于操作
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) {
  //一个+1的小逻辑
    return () => store.dispatch(IncrementAction(payload: 1)); 
  },
  builder: (BuildContext context, VoidCallback callback) {
    return FloatingActionButton(
        onPressed: callback, child: Icon(Icons.add));
  },
),
User对象的展示与操作
展示
StoreConnector<AppState, User>(
  builder: (context, user) {
    return Text(
      user.name,
    );
  },
  converter: (store) => store.state.user
),

逻辑
StoreConnector<AppState, VoidCallback>(
    converter: (Store store) {
        return () => store.dispatch(GetUserAction(payload: User(id:1,name:'我是小明'))); //发送数据
    },
builder: (BuildContext context, VoidCallback callback) {
    return FloatingActionButton(
        onPressed: callback, child: Icon(Icons.add));
    },
),
demo数组的展示于操作
//展示
StoreConnector<AppState, List<DemoList>>(
    converter: (store) => store.state.demo,
    builder: (BuildContext context, demo){
      return new Container(
        height: 500.0,
        child: ListView.builder(
          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),
                ],
              ),
            );
          },
        ),
      );
    },
),
  
//操作

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));
  },
),
  

简单的数据就是这样流通的

由于是刚刚学习,很多不好的地方希望大家能够指出,谢谢🙏