I have a page A that does some tasks for every time interval. I only want to perform these tasks only if page A is active and showing on the screen.
If the screen is showing page B, it will NOT perform the tasks.
How should I approach this problem?
I have a page A that does some tasks for every time interval. I only want to perform these tasks only if page A is active and showing on the screen.
If the screen is showing page B, it will NOT perform the tasks.
How should I approach this problem?
It's fairly simple to do without checking the page stack. Since if it's on top of the page stack is only the case when that page is currently ACTIVe, meaning all other pages are removed (popped) from the stack. If you called for a new page with Navigator.of(context).push...., in order to 'pause' the previous page, you could await that action. The following example will a periodic timer (remember, you have to have it outside of the scope of the function, for example, in the state) and assign it to already existing Timer variable.
Timer t; //a variable in a Stateful widget
@override
void initState() {
super.initState();
//it's initialized somewhere and is already working
t = Timer.periodic(
Duration(milliseconds: 500),
(t) => print(
'CALL YOUR FUNCTION HERE ${t.tick}',
),
);
}
_someMethodInvokingPageB() async {
// Cancel the timer before the opening the second page
// no setState((){}) is needed here
t.cancel();
// Your calling of Page B. Key is the word AWAIT
// AWAIT will pause here until you are on the Page B
var result = await Navigator.of(context).pushNamed('/pageB');
// reassign a timer to your timer
// you don't need setState((){}) here
t = Timer.periodic(
Duration(milliseconds: 500),
(t) => print('CALL YOUR FUNCTION HERE ${t.tick}'),
);
}
That's how you have a timer, you have a method where you open Page B and before opening Page B you cancel that timer, await the opening of Page B and after you finish stuff on Page B, you reassign a new timer to your Timer t variable.
P.S. Don't forget to call t.cancel() in your dispose() method!