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
?
You can add NavigatorKey in your RouterDelegate (Not tested). For those who are looking for GoRouter, navigatorKey can be added in the GoRouter constructor.
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(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With