Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter navigatorkey + GlobalKey: "method 'pushedName' was called on null"

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);
}
like image 329
Joe Fresh Avatar asked Oct 15 '18 17:10

Joe Fresh


1 Answers

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.

like image 126
Zino Hofmann Avatar answered Nov 01 '22 04:11

Zino Hofmann