Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to perform an actions after Navigator.pushNamedAndRemoveUntil() has completed

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.

like image 892
GBerga Avatar asked Oct 27 '25 12:10

GBerga


1 Answers

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();
  }
  
  // ...
}

Using didPush() method

This 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
});
like image 111
Stewie Griffin Avatar answered Oct 30 '25 04:10

Stewie Griffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!