flutter

Flutter - detect when navigating away from the page


I have an app with multiple pages, to which I navigate via Drawer using Navigator.pushNamed.

On one of the pages I have a meditation timer - Timer.periodic which then plays an audio of a bell.

There are scenarios when a user will navigate to another page via Drawer. I cannot figure out how to detect the navigation away so that I stop the timer...

I tried using PopScope (which doesn't fire because back button wasn't used), dispose method on the page state class (which wasn't called because the widget is still in the tree). I also tried printing something in Navigator.pushNamed(...).then method, which doesn't output anything.

What can I do to detect the navigation away? Or is there a different approach?

Many thanks!


Solution

  • I presume that your drawer's widgets will have buttons or listtiles for navigation. So, you just need to add a timer.cancel on the "onTap" function

    Drawer
       ListView
          ListItem
             onTap() {
                timer.cancel(); // <-- this will cancel your timer
                Navigator.push();
             }
          ListItem
             onTap() {
                timer.cancel(); 
                Navigator.push();
             }
    

    Cheers