'NavigatorKey not found on MaterialApp.router

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?



Solution 1:[1]

if you just want a GlobalContext you can use scaffoldMessengerKey instead which is used for showing snack bar.

Note: this BuildContext won't work for navigation

final scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      scaffoldMessengerKey: scaffoldMessengerKey,
    );
  }
}

To access the global context

final context = scaffoldMessengerKey.currentContext!;

Solution 2:[2]

This is an alternative Solution of this Problem :

Add this:

        dependencies:
      one_context: ^1.1.1

then :

OneNotification<List<Locale>>(
      onVisited: (context, localeList) {
        print('widget visited!');
      },
      stopBubbling: true, // avoid the data bubbling to ancestors widgets
      initialData: _localeEnglish, // [data] is null during boot of the application, but you can set initialData
      rebuildOnNull: true, // Allow other entities reload this widget without messing up currenty data (Data is cached on first event)
      builder: (context, localeList) {
        return MaterialApp(
          supportedLocales: localeList,
        );
      },
    );

Here is the Link of this Package kindly have a look .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tasnuva Tavasum oshin