Reputation: 419
I am trying to implement a custom navigation in my Flutter app.
From my main page I have the following routes possible:
Option 1
Main --> dashboard --> user deal list --> deal page --> detail page
Option 2
Main --> login --> dashboard --> user deal list --> deal page --> detail page
The issue I have in option 1 is that when wanting to navigate in option 1 from detail page backwards I want to be able to go to the deal page but the navigation takes me back to Main.
In option 2 after logging in, when on the dashboard, the user should be going to the Main page and not back to the login page.
I have tried using WillPopScope as follows:
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
Navigator.pop(context, MaterialPageRoute(builder: (context) => BuyerDealPage()),);
return false;
},
child: MaterialApp(
home: Scaffold(
But with the above, the app still navigates all the way back to the Main page instead of going back to the deal page.
I tried moving the WillPopScope
below Material app, that doesn’t work either.
Am I using WillPopScope
incorrectly? I though the idea was that WillPopScope
overrides the back button?
I have tried replacing Navigator.pop
with Navigator.push
as well and that doesn’t seem to work either.
Not sure if it helps at all but I have implemented WillPopScope
on all my pages as I wanted to ensure that I specify the back navigation.
Edit: my code on how i am pushing between pages (example for user deal list --> deal page)
Navigator.push(context,MaterialPageRoute(builder: (context) => BuyerDealPage()));
Upvotes: 0
Views: 3478
Reputation: 419
I ended up reworking my navigation by implementing named routes. i then used pushNamedreplacement
in all places where navigation needed to occur. this includes in WillPopScope
. do not use pop.context
instead, use pushnamedreplacement
.
Also, being new to Flutter, i added MaterialApp to each new widget which you should NOT DO.
this causes confusion in the navigation.
Upvotes: 0
Reputation: 369
I think just a standard Navigator.of(context).pop()
should work in your case if you push next pages using Navigator.of(context).push()
or Navigator.of(context).pushNamed()
.
For the second scenario, when you push dashboard page after logging in, you can use Navigator.of(context).pushReplacement()
method, which will replace login page with dashboard page. This way, when you try to go back from dashboard page, you will go directly to Main page.
If you want to achieve the same behavior with Android back button, you need to wrap your page with WillPopScope
just as you did, but in onWillPop
use:
WillPopScope(
onWillPop: () async {
Navigator.of(context).pop();
return false;
},
child: ...yourNextWidgetHere...
Upvotes: 1