admin管理员组

文章数量:1312737

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!

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!

Share Improve this question asked Feb 1 at 15:53 Katya SKatya S 1,3634 gold badges19 silver badges34 bronze badges 2
  • 1 If you don't need the meditation page to keep running in the background you could Navigator.pushReplacement() instead. Doing this would trigger the onDispose method. – thenry Commented Feb 2 at 1:20
  • Thank you for the tip! Useful to know that it'll dispose the previous page – Katya S Commented Feb 2 at 7:09
Add a comment  | 

1 Answer 1

Reset to default 0

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

本文标签: Flutterdetect when navigating away from the pageStack Overflow