Reputation: 3899
I have create running clock using timer with this code :
class LiveClock extends StatefulWidget {
@override
_LiveClockState createState() => _LiveClockState();
}
class _LiveClockState extends State<LiveClock> {
String _timeString;
String _dateString;
Timer _timerClock;
String _formatTime(DateTime dateTime) => DateFormat.Hms().format(dateTime);
String _formatDate(DateTime dateTime) =>
DateFormat.yMMMMEEEEd(appConfig.indonesiaLocale).format(dateTime);
@override
void initState() {
super.initState();
_timeString = _formatTime(DateTime.now());
_dateString = _formatDate(DateTime.now());
_timerClock = Timer.periodic(Duration(seconds: 1), _getTime);
}
@override
void dispose() {
_timerClock.cancel();
super.dispose();
}
void _getTime(Timer timer) {
final DateTime now = DateTime.now();
final String formattedTime = _formatTime(now);
setState(() => _timeString = formattedTime);
}
@override
Widget build(BuildContext context) {
print('This Rebuild');
return Text(
'$_dateString $_timeString ',
textAlign: TextAlign.center,
);
}
}
But the problem is , if i navigate to another screen , the timer still running although i have dispose the timer.
did I make mistake or it's behaviour the timer ?
Upvotes: 2
Views: 3391
Reputation: 258
In flutter, dispose is called on a widget when it is completely removed from the parent tree.
When using routes(navigation) in flutter.
Using push navigation, a new screen is added on top of current screen. hence the tree (of old screen) is not completely destroyed hence dispose is not called.
using pop. the screen is removed so is the tree. hence dispose is called.
hope this helps
Upvotes: 5