Reputation: 134
In my Flutter app, I need to clear the Navigator stack and get back to the Home page when a certain button is pressed. To achieve that I've used Navigator.pushNamedAndRemoveUntil(context, "/", (r) => false);
. I also need to call a function after the navigation has been completed, meaning that I'm now on the Home page.
I've tried calling the .whenComplete()
method on Navigator.pushNamedAndRemoveUntil()
, but it doesn't seem to work.
Thanks in advance.
Upvotes: 3
Views: 4954
Reputation: 5608
I'd say use your function inside dipose()
, so it's called when the widget is removed from the tree as you navigate to another screen.
class _MyPageState extends State<MyPage> {
// ...
// Some code
@override
void dispose() {
// Insert your function here
super.dispose();
}
// ...
}
didPush()
methodThis can be used to call your function after navigating to another screen because it returns when the push transition is complete. However, you have to do it with pushAndRemoveUntil()
instead of pushNamedAndRemoveUntil()
. So, you can create a PageRoute
which provides didPush()
method.
// Create your route
MaterialPageRoute route = MaterialPageRoute(
builder: (context) => HomePage(),
);
// Push the route onto the navigator, and then remove all the previous routes
Navigator.pushAndRemoveUntil(context, route, (r) => false);
// This returns when the push transition is complete.
route.didPush().whenComplete(() {
// Insert your function here
});
Upvotes: 5
Reputation: 323
You can try as well as this code And please let me know.
gotoNewPage(context) async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
NewPage()));
/// Your logic is here.
}
Upvotes: -1