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

Issue

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.

Solution

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
});

Answered By – Stewie Griffin

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *