14

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?

Dani
  • 3,128
  • 2
  • 43
  • 91
  • 2
    Take a look at this https://stackoverflow.com/questions/49869873/flutter-update-widgets-on-resume – Steve Dec 20 '19 at 10:53
  • @Steve - The question is about navigating back from the activity within the same application, but not about coming back to the application. Your link is not valid in the context of the question. – Stack Overflow Oct 30 '22 at 19:56
  • Thank you. This comment was posted a long time ago and I didn't realize my mistake. – Steve Nov 01 '22 at 11:45

3 Answers3

41
Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => NextPage(),
    ),
  ).then((_){
// Here you will get callback after coming back from NextPage()
// Do your code here
});
Jay Mungara
  • 6,663
  • 2
  • 27
  • 49
9

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");
}
Crazy Lazy Cat
  • 13,595
  • 4
  • 30
  • 54
3

Another solution, which is more verbose but also more efficient if you push a lot of Routes from the same Widget, would be to create your own NavigatorObserver.

1- Create your NavigatorObserver

final routeObserver = MyRouteObserver();

class MyRouteObserver extends NavigatorObserver {
  final Set<RouteAware> _listeners = <RouteAware>{};

  void subscribe(RouteAware routeAware) {
    _listeners.add(routeAware);
  }

  void unsubscribe(RouteAware routeAware) {
    _listeners.remove(routeAware);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    for (var listener in _listeners) {
      listener.didPop();
    }
  }
}

2- Add it to your MaterialApp

  return MaterialApp(
      navigatorObservers: [routeObserver],
...

3- Implement RouteAware in the Widget where you want to listen to Navigation events, and subscribe/unsubscribe to your routeObserver

class _TablePageState extends State<TablePage> implements RouteAware {

  @override
  void initState() {
    super.initState();
    routeObserver.subscribe(this);
  }


  @override
  Widget build(BuildContext context) {
    return Container();
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPop() {
    //This method will be called from your observer
  }

  @override
  void didPopNext() {}

  @override
  void didPush() {}

  @override
  void didPushNext() {}
}
FDuhen
  • 4,097
  • 1
  • 15
  • 26