简体   繁体   中英

how to stop Timer.periodic that started inside initState when leaving the page flutter

I'm running 2 timers in my initState function, here is the code:

  @override
  void initState() {
    readingSavedData();
    _timeString = _formatDateTime(DateTime.now());
    Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime());
    Timer.periodic(Duration(seconds: 3), (Timer t) => gettingLocation());
    super.initState();

as this _getTime() functions are running setState() every 1 second on a Text widget that shows a timer.

The problem that it never stops when I leave the page using Navigator .. it keeps running and popping this error in the console :

Unhandled Exception: setState() called after dispose()

as it can't call setSatate(){} on a widget that is not visible anymore. how to avoid this.

Based on @pskink answer, i solved it using this method :

  Timer _clockTimer;
  Timer _locationTimer;
  @override
  void initState() {
    readingSavedData();
    _timeString = _formatDateTime(DateTime.now());
    _clockTimer = Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime());
    _locationTimer = Timer.periodic(Duration(seconds: 3), (Timer t) => gettingLocation());
    super.initState();
  }

  @override
  void dispose() {
    _clockTimer.cancel();
    _locationTimer.cancel();
    super.dispose();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM