Skip to content

Instantly share code, notes, and snippets.

@it-one-mm
Last active September 23, 2020 09:12
Show Gist options
  • Save it-one-mm/ab7bfaff6cb8ed1cad270f76709b7c02 to your computer and use it in GitHub Desktop.
Save it-one-mm/ab7bfaff6cb8ed1cad270f76709b7c02 to your computer and use it in GitHub Desktop.
Change Route like Viu using Drawer
void _changeRoute(BuildContext context, String newRouteName) {
print('newRouteName: $newRouteName');
// Close drawer
Navigator.pop(context);
// Check current screen status
bool currentRouteIsHome = false;
bool currentRouteIsNewRoute = false;
Navigator.popUntil(context, (currentRoute) {
print('currentRoute: ${currentRoute.settings.name}');
// This is just a way to access currentRoute; the top route in the
// Navigator stack.
if (currentRoute.settings.name == Routes.categories) {
currentRouteIsHome = true;
}
if (currentRoute.settings.name == newRouteName) {
currentRouteIsNewRoute = true;
}
// Return true so popUntil() pops nothing.
return true;
});
print('currentRouteIsHome: $currentRouteIsHome');
print('currentRouteIsNewRoute: $currentRouteIsNewRoute');
// Switch screen
if (!currentRouteIsNewRoute) {
// Only switch screen if new route is different from current route.
if (currentRouteIsHome) {
// Navigate from home to non-home screen.
Navigator.pushNamed(context, newRouteName);
} else {
if (newRouteName == Routes.categories) {
// Navigate from non-home screen to home.
Navigator.pop(context);
} else {
// Navigate from non-home screen to non-home screen.
Navigator.popAndPushNamed(context, newRouteName);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment