如何使用async_redux实现路线导航

时间:2019-08-21 23:45:39

标签: asynchronous flutter redux

我是Flutter和Dart的新手,并且在https://pub.dev/packages/async_redux中找到了一个新的“ async_redux”包,以比传统的“ redux”包更轻松地开发项目。在自述文件中,有关于工具路线导航的简短描述,但我总是收到:

“类型“ NavigateAction”不是“动作”的类型“ ReduxAction”的子类型”

当我在“ onChangePage”中使用-dispatch(NavigateAction.pushNamed(“ MyRoute”))-时。

这里的结构代码:


Store<AppState> store;
final navigatorKey = GlobalKey<NavigatorState>();

void main() async{
  NavigateAction.setNavigatorKey(navigatorKey);
  var state = AppState.initialState();
  store = Store<AppState>(initialState: state);
  runApp(MyApp());
}

final routes={
  '/': (BuildContext context) => First(),
  "/myRoute": (BuildContext context) => Two(),
};

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StoreProvider<AppState>(
      store: store,
      child: MaterialApp(
        routes: routes,
        navigatorKey: navigatorKey,
      ),
    );
  }
}

class AppState {
  AppState(...);
  AppState copy(...) =>
      AppState(
        ...
      );
  static AppState initialState() => AppState(
    ...
  );
  @override
  bool operator ==(Object other) =>    ...
  @override
  int get hashCode => ...;
}

class First extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MyHomePageConnector();
}

class MyHomePageConnector extends StatelessWidget {
  MyHomePageConnector({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, ViewModel>(
      model: ViewModel(),
      builder: (BuildContext context, ViewModel vm) => MyHomePage(
        onChangePage: vm.onChangePage
      ),
    );
  }
}

class ViewModel extends BaseModel<AppState> {
  ViewModel()
  VoidCallback onChangePage;
  ViewModel.build({
    @required this.onChangePage,
  }) : super(equals: []);

  @override
  ViewModel fromStore() => ViewModel.build(
    onChangePage: () => dispatch (NavigateAction.pushNamed ("/myRoute"))
  );
}

class MyHomePage extends StatefulWidget {
  final VoidCallback onChangePage;
  MyHomePage({
    Key key,
    this.onChangePage
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
  }

@override
  Widget build(BuildContext context) {
    return RaisedButton(
       child: Icon(Icons.add_circle),
           onPressed: widget.onChangePage
           ),  
    );
  }
}

如何以及在何处实现“ dispatch(NavigateAction.pushNamed(“ / myRoute”))“?

1 个答案:

答案 0 :(得分:2)

尝试一下:

dispatch(NavigateAction<AppState>.pushNamed("/myRoute"))"

更新

有了最近的async_redux: ^1.2.0,您就不再需要<AppState>了,可以像这样发送它:

dispatch(NavigateAction.pushNamed("/myRoute"))"