【Flutter】Timer中に画面遷移するとエラーを吐く

プログラミング

はじめに

FlutterでTimerWidgetを使用している状態で画面遷移をすると下記エラーを吐く。

[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: setState() called after dispose(): _endOfTimerState#78f55(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
#0      State.setState.<anonymous closure> (package:flutter/src/widgets/frame<…>

原因

画面遷移した時、遷移元のWidgetは消えるがTimerだけ残り続けてしまうため。

解決策

画面遷移が発生した時はタイマーも停止する

Widgetのライフサイクルは

  1. initState()
  2. build()
  3. dispose()

の順番で実行されます。dispose()は画面遷移などでWidgetが消滅する時に実行されます。

なのでdisposeにタイマーを止める処理を記述してあげましょう。

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

タイトルとURLをコピーしました