Flutter - Adding responsive_framework to MaterialApp causing navigation key to be null

676 Views Asked by At

I'm trying to add responsive_framework to my app.

When I change my MaterialApp from this:

    return MaterialApp(
            theme: lightTheme,
            darkTheme: darkTheme,
            navigatorKey: globalKey,
            onGenerateRoute: (settings) {
              return AppRoutes.onGenerateRoute(settings, ref);
            },
            builder: (_, child) {
              return child!;
            });
}

To this:

return MaterialApp(
            theme: lightTheme,
            darkTheme: darkTheme,
            navigatorKey: globalKey,
            onGenerateRoute: (settings) {
              return AppRoutes.onGenerateRoute(settings, ref);
            },
            builder: (context, child) {
              return ResponsiveWrapper.builder(
                  BouncingScrollWrapper(child: child!),
                  breakpoints: const [
                    ResponsiveBreakpoint.resize(350, name: MOBILE),
                    ResponsiveBreakpoint.autoScale(600, name: TABLET),
                    ResponsiveBreakpoint.resize(800, name: DESKTOP),
                    ResponsiveBreakpoint.autoScale(1700, name: 'XL'),
                  ]);
            });

To add Flutter responsive_framework to my app, it causes my navigation key to be null.

The key is global: final globalKey = GlobalKey<NavigatorState>();

And there is a getter in the class that has the MaterialApp:

NavigatorState? get _navigator => globalKey.currentState;

And there is code that navigates to the home page with that key:

_navigator!.pushNamedAndRemoveUntil(LOGGED_OUT_HOME, (route) => false); which throws a null exception on _navigator.

Anyone know why changing my MaterialApp to return a ResponsiveWrappercaused that to happen?

1

There are 1 best solutions below

0
On

I think responsive_framework seems to cause my MaterialApp to initialise a little bit slower which populates my globalKey slower. I added a null check with a delay, before using the key to navigate. Hacky, but got me unblocked.

  if (_navigator == null) {
    Future.delayed(const Duration(milliseconds: 100), () {
      if (_navigator != null) {
        pushRoute(authStatus);
      }
    });
  } else {
    pushRoute(authStatus);
  }