Flutter Redux Navigator GlobalKey.currentState ret

2019-02-27 12:08发布

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
2楼-- · 2019-02-27 12:56

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);
  };
}
查看更多
登录 后发表回答