Flutter: Run callback when returning to page

Here's how you can run a callback / function when returning to a page after navigating.

Problem

Sometimes you want to run a function / callback when you return to a page. This doesn't necessarily have to involve complex state management. It can be as simple as the following:

Solution

Note: In the following example, I'm using CupertinoPageRoute because I like the swipe back benefit you get, plus I prefer the animation style to Android's default.

Anyway, when writing your navigation code, simply add a "then()" clause to the end like so, where MyPage is the page component you're navigating to:

Navigator.of(context).push(
  CupertinoPageRoute(
    builder: (context) => MyPage(),
  ),
).then((_) {
  // this will run when you navigate BACK to this page, so do something here.
});

This looks like Promises from JavaScript, so you'd be forgiven for thinking that this block will execute as soon as the navigation to MyPage() has finished, but it's actually more of a "when the user is done with the page I'm navigating to, then do something" thing.

Admittedly, this is confusing, but once you remember this little detail, it's pretty useful.

Now, whenever you navigate back to this page, anything inside that "then()" block will be executed. Simple, effective and works.

Conclusion

Not everything has to be complex, use over-engineered state management techniques to get stuff done.

Hope this helps!

Comments: