I am using global key to handle my navigations. The main.dart, routes and NavigationService are as below. The main purpose of using the global keys is to make the navigation independent of context so that the network modules can auto log user out via the dio interceptor if the refresh token expires.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'AZY APP',
navigatorKey: locator<NavigationService>().navigatorKey,
onGenerateRoute: router.generateRoute,
home: HomePageScreen())
}}
NavigationService.dart
class NavigationService {
final GlobalKey<NavigatorState> navigatorKey =
new GlobalKey<NavigatorState>();
Future<dynamic> navigateTo(String routeName, {dynamic arguments}) {
return navigatorKey.currentState.pushNamed(routeName, arguments: arguments);
}
pop(value) {
print("pop");
return navigatorKey.currentState.pop(value);
}
goBack() {
print("goback");
return navigatorKey.currentState.pop();
}
popUntil(String desiredRoute) {
return navigatorKey.currentState.popUntil((route) {
print("${route.settings.name}");
return route.settings.name == desiredRoute;
});
}
pushReplacementNamed(String route) {
print("pushReplacementNamed");
return navigatorKey.currentState.pushReplacementNamed(route);
}
}
Routes.dart
Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case routes.SplashScreenRoute:
return MaterialPageRoute(builder: (context) => SplashScreen());
case routes.LoginScreenRoute:
return MaterialPageRoute(builder: (context) => LoginScreen());
case routes.MainPageScreenRoute:
return MaterialPageRoute(builder: (context) => MainPageScreen());
case routes.HomePageScreenRoute:
return MaterialPageRoute(builder: (context) => HomePageScreen());
default:
return MaterialPageRoute(
builder: (context) => Scaffold(
body: Center(
child: Text('Error Loading Screen'),
),
),
);
}
}
All the functions in NavigationService works well except popUntil. For every route, settings.name is null so i am unable to using navigatorkey with popUntil.
Log of print("${route.settings.name}").
The problem was that I was not passing route settings to MaterialPageRoute in my router.
MaterialPageRoute(
settings: settings, builder: (context) => SplashScreen());
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