Flutter Redux Navigator GlobalKey.currentState returns null

混江龙づ霸主 提交于 2019-12-19 09:48:04

问题


I am developing Flutter with Redux.

When a user starts an application, I want Redux to automatically dispatch an action. This action will make the Navigator push different routes dependently.

This snippet provided by a Flutter dev member uses the GlobalKey to use the Navigator inside the middleware.

Following this, I organize my code as follows:

main.dart

void main() {
  final store = new Store(appStateReducer,
      middleware:createRouteMiddleware()
  );
  runApp(new MyApp(store));
}

class MyApp extends StatelessWidget {
  final Store<AppState> store;

  MyApp(this.store);

  @override
  Widget build(BuildContext context) {
    return new StoreProvider<AppState>(
        store: store,
        child: MaterialApp(
            routes: {
              Routes.REGISTER: (context) {
                return RegisterScreenContainer();
              },
              Routes.SET_PROFILE: (context) {
                return SetProfileScreenContainer();
              },
              //Routes.HOME = "/" so this route will be run first
              Routes.HOME: (context) {
                return StoreBuilder<AppState>(
                  //onInit is called to dispatch an action automatically when the application starts. The middleware will catch this and navigate to the appropriate route.
                  onInit: (store) => store.dispatch(
                      ChangeRoute(routeStateType: RouteStateType.Register)),
                  builder: (BuildContext context, Store vm) {
                    return RegisterScreenContainer();
                  },
                );
              },
            }));
  }
}

middleware.dart

Middleware<AppState> createRouteMiddleware(
    {@required GlobalKey<NavigatorState> navigatorKey}) {
  final changeRoute = _createChangeRouteMiddleware(navigatorKey: navigatorKey);
  return TypedMiddleware<AppState, ChangeRoute>(changeRoute);
}

Middleware<AppState> _createChangeRouteMiddleware(
    {@required GlobalKey<NavigatorState> navigatorKey}) {
  print(navigatorKey.currentState);
  return (Store store, action, NextDispatcher next) async {
    switch ((action.routeStateType as RouteStateType)) {
      case RouteStateType.Home:
        navigatorKey.currentState.pushNamed(Routes.HOME);
        break;
      case RouteStateType.Register:
        //The middleware intercepts and push the appropriate route depending on the action
        navigatorKey.currentState.pushNamed(Routes.REGISTER);
        break;
      default:
        break;
    }
    next(action);
  };
}

And this is the error I got

[ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception: E/flutter ( 2544): NoSuchMethodError: The method 'pushNamed' was called on null. E/flutter ( 2544): Receiver: null E/flutter ( 2544): Tried calling: pushNamed("/register")

This means that the action was successfully dispatched, however, the currentState of the navigatorKey was null.

What am I missing here?

Note that I am aware of this seemingly similar question which does not really apply to my question. Even when I merge the main.dart and middleware.dart into one file, it still doesn't work.


回答1:


I solwed this issue by having the global navigator key in a separate file. Then I used that in my materialApp and in the middleware.

I put the navigator key in my keys.dart file:

import 'package:flutter/widgets.dart';
class NoomiKeys {
  static final navKey = new GlobalKey<NavigatorState>();
}

Added the key to MaterialApp widget "navigatorKey: NoomiKeys.navKey," in my main.dart file (alot of code is removed to make it faster to read):

import 'package:noomi_nursing_home_app/keys.dart';


@override
Widget build(BuildContext context) {
return StoreProvider<AppState>(
  store: store,
  child: MaterialApp(

    //Add the key to your materialApp widget
    navigatorKey: NoomiKeys.navKey,

    localizationsDelegates: [NoomiLocalizationsDelegate()],
    onGenerateRoute: (RouteSettings settings) {
      switch (settings.name) {

And use it in navigate_middleware.dart;

import 'package:noomi_nursing_home_app/actions/actions.dart';
import 'package:noomi_nursing_home_app/keys.dart';
import 'package:redux/redux.dart';
import 'package:noomi_nursing_home_app/models/models.dart';

List<Middleware<AppState>> navigateMiddleware() {

  final navigatorKey = NoomiKeys.navKey;

  final navigatePushNamed = _navigatePushNamed(navigatorKey);
  return ([
    TypedMiddleware<AppState, NavigatePushNamedAction>(navigatePushNamed),
  ]);
}

Middleware<AppState> _navigatePushNamed(navigatorKey) {
  return (Store<AppState> store, action, NextDispatcher next) {
    next(action);
    navigatorKey.currentState.pushNamed(action.to);
  };
}



回答2:


looks like you forgot to declare & pass navigatorKey to middleware

final navigatorKey = GlobalKey<NavigatorState>();
void main() {
  final store = Store(appStateReducer,
      middleware:createRouteMiddleware(navigatorKey: navigatorKey)
  );
  runApp(MyApp(store));
}

and your MaterialApp is missing navigatorKey too

MaterialApp(
  navigatorKey: navigatorKey
  routes: /* your routes */
)


来源:https://stackoverflow.com/questions/50303441/flutter-redux-navigator-globalkey-currentstate-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!