I am implementing a timer in flutter .Here is the structure of the app.
Page A (Contains some lists where user clicks and takes it to timer Page). Page B formats ,runs the timer .I am able to run the timer/stopwatch properly,but when i press the back button on Page B I get the setstate() called after dispose error.I understand that this is the expected behaviour. If i use timer.cancel() on dispose I wont be getting the error ,but the timer will stop running.The timer/stopwatch should continue to run even if i navigate to Page A or say any other new page(widget). I know that this may be possible using listeners and WidgetBindingObserver,But i have no clear knowledge of implementing it.Hope I'll get some help on this issue.
Build class of page B:
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: new IconButton(icon: new Icon(Icons.arrow_back), onPressed: ()async{
Navigator.pop(context,widget._elapsedTime);
}),
title: Text("widget.title"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$_elapsedTime'),
RaisedButton(
child: Text('Start'),
onPressed: () {
if(watch.isRunning){
stopWatch();
}
else{
startWatch();
}
},
),
],
),
));
StartWatch function:
startWatch() {
watch.start();
timer = new Timer.periodic(new Duration(milliseconds:1000), updateTime);}
Update Time function which gets called every second:
updateTime(Timer timer) {
if (watch.isRunning) {
print(_elapsedTime);
var time= formatedTime(watch.elapsedMilliseconds);
print("time is"+time);
setState(() {
_elapsedTime = time;
});
}