12

I've found the "GlobalKey NavigatorState" solution for middleware here but was unable to overcome the error "The method 'pushedNamed' was called on null". I then found this alternative solution to fix the issue using a separate class and static variable, but it yielded the same error. All I really need is a very basic example of the setup and how to call the "pushedNamed" function somewhere else.

Current code

initialize GlobalKey in separate folder:

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);
}
Delgan
  • 18,571
  • 11
  • 90
  • 141
Joe Fresh
  • 121
  • 1
  • 1
  • 4
  • You'll get this error if an `UpdateRoomStatus` action is dispatched before your app renders for the first time. You have to wait until the key is attached to the navigator before you can use it. – Kirollos Morkos Oct 15 '18 at 18:19
  • i had the same error, but my issue was that i used "key" instead of "navigatorKey" in my MaterialApp – Leonard Arnold Dec 28 '18 at 18:06

1 Answers1

9

Had the same issue, the last line in the docs seems to give a hint for the fix.

navigatorKey property

You apparently can't use routes with a navigatorKey and must use onGenerateRoute.

Zino Hofmann
  • 145
  • 1
  • 9
  • after 3 hours, found your answer and solution, thanks – Leandro Hoffmann Apr 13 '20 at 18:11
  • 5
    @ZinoHofmann you dont give any code examples and give a poor explanation. I wouldnt of checked it either – Llama May 19 '21 at 03:23
  • ah....we use routes / goRouter....hm, what's the way to go to a route in other parts of an app? Specifically from main (I am using a listener for deep links to then determine routes) – satchel Jul 12 '22 at 05:28