Flutter Redux Navigator GlobalKey.currentState devuelve nulo
Estoy desarrollando Flutter con Redux.
Cuando un usuario inicia una aplicación, quieroRedux
a @ automáticamendispatch
unaction
. Esta acción hará que laNavigator
empuje diferentes rutas de forma dependiente.
Este fragmentoproporcionado por un miembro de desarrollo de Flutter usa elGlobalKey
usar elNavigator
dentro demiddleware
.
Siguiendo esto, organizo mi código de la siguiente manera:
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);
};
}
Y este es el error que obtuve
[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")
Esto significa que elaction
fue enviado con éxito, sin embargo, elcurrentState
delnavigatorKey
fuenull
.
¿Que me estoy perdiendo aqui
Nota que soy consciente deesta pregunta aparentemente similar que no se aplica realmente a mi pregunta. Incluso cuando fusiono la main.dart y middleware.dart en un archivo, todavía no funciona.