redux作用:定义一个全局数据 数据变化 页面中用到的地方会自动刷新 有点像vue中vuex
使用步骤
1.定义数据bean类
class GSYState{
///用户信息
User? userInfo;
///是否登录
bool? login;
GSYState({this.userInfo, this.login});
}
2.创建reducer
这个是全局统一管理的reducer
///创建 Reducer
GSYState appReducer(GSYState state, action) {
return GSYState(
///通过 UserReducer 将 GSYState 内的 userInfo 和 action 关联在一起
userInfo: UserReducer(state.userInfo, action),
login: LoginReducer(state.login, action),
);
}
.单个reducer
final UserReducer = combineReducers<User?>([
TypedReducer<User?, UpdateUserAction>(_updateLoaded),
]);
User? _updateLoaded(User? user, action) {
user = action.userInfo;
return user;
}
class UpdateUserAction{
User? userInfo;
UpdateUserAction(this.userInfo);
}
TypedReducer 作用:将reducer的处理逻辑与定义的 Action绑定
combineReducers 作用:通过 TypedReducer 将 UpdateUserAction 与 reducers 关联起来
3.创建store
final store = Store<GSYState>(appReducer, initialState: GSYState(userInfo: User("name","1"), login: false));
4.将Store放入顶层
class MyAppState extends State<MyAppful> {
final store = Store<GSYState>(appReducer,
initialState: GSYState(userInfo: User("name", "1"), login: false));
@override
Widget build(BuildContext context) {
return StoreProvider(
store: store,
child: MaterialApp(
routes: {
FirstPage.sName: (context) {
return FirstPage();
},
SecondPage.sName: (context) {
return SecondPage();
},
},
title: "ahahh",
theme: ThemeData(
primarySwatch: Colors.blue,
),
));
}
}
就是用StoreProvider包裹一个 把store传进去 store包含了数据bean类,和数据变化的规则reducer
5.使用数据
class FirstPageState extends State<FirstPage> {
@override
Widget build(BuildContext context) {
return StoreConnector<GSYState, User?>(
converter: (store) {
return store.state.userInfo;
},
builder: (context, userInfo) {
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () {
Navigator.pushNamed(context, SecondPage.sName);
},
child: Text(userInfo!.name!),
),
),
);
},
);
}
}
用StoreConnector包裹一下
5.发送数据变化Action
class SecondPageState extends State<SecondPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: StoreConnector<GSYState, VoidCallback>(
converter: (store) {
return () {
store.dispatch(UpdateUserAction(User("哈哈哈", "12")));
Navigator.pop(context);
};
},
builder: (context, callback) {
return Center(
child: GestureDetector(
onTap: callback,
child: Text("第二个页面"),
),
);
},
),
);
}
}
关键点:用StoreConnector包裹拿到store,调用store.dispatch();发送action 参数是想发送变化的action 把参数带过去