'Detect when we moved back to previous page in Flutter

We moved from Page1 to Page2 but now from Page2 we move back again to Page1 like this:

Navigator.of(context).pop();

How can we detect on Page1 that we went back?



Solution 1:[1]

Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => NextPage(),
    ),
  ).then((_){
// Here you will get callback after coming back from NextPage()
// Do your code here
});

Solution 2:[2]

In your Page1, When you push Page2 wait for it to pop

Future<void> _goToPage2() async {
  await Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => Page2(),
    ),
  );
  print("Page2 is popped");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jay Mungara
Solution 2