Zeffry Reynando
Zeffry Reynando

Reputation: 3899

Flutter : Cancel Timer In Dispose Not Working

I have create running clock using timer with this code :

Source 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,
    );
  }
}

Result

But the problem is , if i navigate to another screen , the timer still running although i have dispose the timer.

enter image description here

did I make mistake or it's behaviour the timer ?

Upvotes: 2

Views: 3391

Answers (1)

bhanu
bhanu

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.

  • using push replacement. new screen replaces old screen deleting the widget tree. so dispose is called.

hope this helps

Upvotes: 5

Related Questions