首页 > 解决方案 > 如何使用 async_redux 实现路由导航

问题描述

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

“类型'NavigateAction'不是'action'的'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"))”?

标签: flutterasynchronousreduxasync-redux

解决方案


尝试这个:

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

更新:

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

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

推荐阅读