Episode - 16 Go to Previous Page
In application coming to the previous page is also important as much as going to the next page. So lets us create a function that will handle the poping of the pages. Create a private function with name
_handlePopPage()
which return a bool value. This Function has two parameters route and result. The route parameter is the current route and has all the route information like route settings from which we can retrive the name and other arguments. And the result parameter is a callback result that we get after we have popped the page.
We call a didPop function from the PopNavigatorRouterDelegateMixin that we mixed in this class and pass the result into the condition. If the condition is false : That means that pages were not popped. We return a false value. Else we return true and have to handle the pages on how and what we pop and trigger the appropriate state change.
bool _handelPopPages(Route<dynamic> route, result) {
if (!route.didPop(result)) {
return false;
}
}
In the Navigator widget that we have passed in the build function pass this function to the parameter onPoppage:
@override
Widget build(BuildContext context) {
return Navigator(
onPopPage: _handelPopPages,
key: navigatorKey,
pages: [],
);
}
Now that our navigation is done, we must also handle what happens when the back button is pressed. For this navigate to book_router_delegate.dart and scroll down to out _handelPopPages function that we have created.
As you can see our _handelPopPages function is blank. We will pop the pages based on the some condition. Our _handelPopPages function has a route parameter. This route parameter has a settings parameter which has a name parameter. We will retrive the name of the route from this. We will get the name of router and then we will pass condition to check on which screen we are and on which screen we have to go.
bool _handelPopPages(Route<dynamic> route, result) {
if (!route.didPop(result)) {
return false;
}
if (route.settings.name == BookPages.loginPath ||
route.settings.name == BookPages.signupPath ||
route.settings.name == BookPages.homePath) {
appStateManager.logout();
}
if (route.settings.name == BookPages.detailsPath) {
bookManager.bookTapped(-1);
}
if (route.settings.name == BookPages.cartPath) {
appStateManager.onCartTapped(false);
}
if (route.settings.name == BookPages.settingsPath) {
appStateManager.onSettingTapped(false);
}
if (route.settings.name == BookPages.checkoutPath) {
appStateManager.onCheckoutTapped(false);
}
if (route.settings.name == BookPages.mybooksPath) {
appStateManager.onMyBookTapped(false);
}
if (route.settings.name == BookPages.readBookPath) {
appStateManager.onReadBookTapped(false);
}
return true;
}