Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NavigatorKey not found on MaterialApp.router

Tags:

flutter

Previously using MaterialApp there was a way to set a GlobalContext using a NavigatorKey located on the MaterialApp widget.

However now it's looks like that alternative is no longer possible, I have this structure, following Navigator 2.0

Widget build(BuildContext context, WidgetRef ref) {
    return MaterialApp.router(
        debugShowCheckedModeBanner: false,
        restorationScopeId: 'app',
        localizationsDelegates: const [
          AppLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        supportedLocales: AppLocalizations.supportedLocales,
        onGenerateTitle: (BuildContext context) =>
            AppLocalizations.of(context)!.appTitle,
        routeInformationParser: const RoutemasterParser(),
        routeInformationProvider: routeInformationProvider,
        routerDelegate: introductionRouteMap(context, ref));
  }

Now there isn't any NavigatorKey. So my question is, how can I set a GlobalContext using MaterialApp.router?

like image 538
Luis Cardoza Bird Avatar asked Sep 13 '25 13:09

Luis Cardoza Bird


2 Answers

You can add NavigatorKey in your RouterDelegate (Not tested). For those who are looking for GoRouter, navigatorKey can be added in the GoRouter constructor.

like image 110
Sabeer Avatar answered Sep 15 '25 04:09

Sabeer


Here, you can declare the GlobalKey at the top of main.dart or any other location.

 final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

Then you can initialize this navigation key inside GoRouter like this:

...
static GoRouter routes = GoRouter(
navigatorKey: navigatorKey,
routes: [
  GoRoute(
...

Then you can use it like this.

 navigatorKey.currentState?.push(...);
like image 29
Deepak Sapkota Avatar answered Sep 15 '25 03:09

Deepak Sapkota