我已经找到了"GlobalKey NavigatorState" solution for middleware here,但是无法克服错误“方法'pushedNamed'被调用为null”的错误。然后,我使用单独的类和静态变量找到了这个alternative solution to fix the issue,但它产生了相同的错误。 我真正需要的只是一个非常基本的示例设置,以及如何在其他地方调用“pushedNamed”功能。

当前代码

在单独的文件夹中初始化GlobalKey:

class NavKey{
  static final navKey = new GlobalKey<NavigatorState>();
}

main.dart:
import 'package:eumag/assets/tools/route_navigation_constants.dart';

    ...

  @override
  Widget build(BuildContext context) {
    return StoreProvider<AppState>(
      store: store,
      child: MaterialApp(
        theme: ThemeData.dark(),
        navigatorKey: NavKey.navKey,
        routes: <String, WidgetBuilder>{
          ROUTE_LOGIN_PAGE: (BuildContext context) => LoginPage(store),
          ROUTE_MAIN_PAGE: (BuildContext context) => MainPage(store),
        },
        home: StoreBuilder<AppState>(
          builder: (BuildContext context, Store<AppState> store) =>
              LoginPage(store),
        ),
      ),
    );
  }

middleware.dart:
import 'package:eumag/assets/tools/route_navigation_constants.dart';

void appStateMiddleware (Store<AppState> store, action, NextDispatcher next) async{

  final navigatorKey = NavKey.navKey;

  if (action is UpdateRoomStatus){
    navigatorKey.currentState.pushNamed(ROUTE_MAIN_PAGE);
    store.dispatch(createSocketConnection);
  }
  next(action);
}

最佳答案

遇到相同的问题,文档中的最后一行似乎为修复提供了提示。

navigatorKey property

您显然不能将routesnavigatorKey一起使用,而必须使用onGenerateRoute

10-06 09:08