I have my configuration class of my routes to which I am using it through modules like the code below:
class RouterRegister {
static RouterRegister? _instance;
static RouterRegister getIntance() {
return _instance ??= RouterRegister();
}
final RouterConfig<Object> router = GoRouter(
navigatorKey: GlobalKey<NavigatorState>(),
initialLocation: '/',
observers: [
FirebaseAnalyticsObserver(analytics: FirebaseAnalytics.instance)
],
routes: <RouteBase>[
ShellRoute(
builder: (context, __, child) => child,
routes: [
...MicroAuthRoutes.getIntance().routes,
],
)
],
);
}
Where my MicroAuthRoutes class is this:
class MicroAuthRoutes {
static const splash = '/';
static const login = '/login';
static const forgot = '/forgot';
static const signup = '/signup';
static const token = '/token';
static MicroAuthRoutes? instance;
static MicroAuthRoutes getIntance() {
return instance ??= MicroAuthRoutes();
}
final List<RouteBase> routes = [
GoRoute(
path: splash,
pageBuilder: (context, state) {
return MaterialPage(
child: AuthSplashPage(),
);
}),
GoRoute(
path: login,
pageBuilder: (_, state) {
return MaterialPage(
child: AuthLoginPage(),
);
},
),
GoRoute(
path: forgot,
pageBuilder: (_, state) {
return MaterialPage(
child: AuthForgotPage(),
);
},
),
GoRoute(
path: signup,
pageBuilder: (_, state) {
return MaterialPage(
child: AuthSignupPage(),
);
},
),
GoRoute(
path: token,
pageBuilder: (_, state) {
return MaterialPage(
child: AuthTokenPage(),
);
},
),
];
}
And not my main file like this:
final _router = RouterRegister.getIntance().router;
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
@override
void initState() {
super.initState();
AuthState().checkAuthState();
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(
debugShowCheckedModeBanner: false,
routerConfig: _router,
debugShowMaterialGrid: false,
);
}
}
My question is how I can navigate through my controller using the go router but without using the context I didn't find anything in my searches and I'm stuck on this question.
I've tried using the navigator key but I haven't had any success.
Declare NavigatorKey
as a global variable.
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Register it.
final RouterConfig<Object> router = GoRouter(
navigatorKey: navigatorKey,
// rest of code
Now use the key to get the context.
final context = navigatorKey.currentContext;
if (context != null) {
context.go('yourRoute');
}
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