2

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 ?

3
  • Hi, I have the same problem with you... I use bottom tab navigator and timer... have you found the solution of your question? Commented Jul 27, 2020 at 4:16
  • 1
    @uyhaW i change from timer to streambuilder to implement live clock. gist.github.com/zgramming/963c2c79fda867dcb0388a86e8787f6d Commented Jul 27, 2020 at 4:21
  • @ZeffryReynaldo Thanks for your help.. I will try to do the same Commented Jul 27, 2020 at 4:23

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

make sense. In my case i navigate between Widget with BottomNavigationBar. So with it , the timer Will not cancel? Because i worry about memory leak if i leave timer still running

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.