見出し画像

Flutter AnimationControllerのdispose()で詰まった件

起こったこと

The following assertion was thrown while finalizing the widget tree:

<Widgetクラスの名前>#<hogehoge>(tickers: tracking 2 tickers) was disposed with an active Ticker.

<Widgetクラスの名前>created a Ticker via its TickerProviderStateMixin, but at the time dispose() was called on the mixin, that Ticker was still active. 
All Tickers must be disposed before calling super.dispose(). 
Tickers used by AnimationControllers should be disposed by calling dispose() on the AnimationController itself. Otherwise, the ticker will leak.

こんな感じのエラーが出てきて、色々調べたのでまとめる。

Stateful Widget のライフサイクル

Stateful Widgetは以下の10このステップをサイクルしているらしい

1. createState()
2. mounted == true
3. initState()
4. didChangeDependencies()
5. build()
6. didUpdateWidget()
7. setState()
8. deactivate()
9. dispose()
10. mounted == false

dispose()について

エラーを読んでみると、

dispose() がmixinによって呼び出されたけど、Tickerがまたアクティブだった。
 super.dispose() を呼び出す前に、すべてのTickerを破棄する必要がある。
AnimationControllerによって使用されるTickerは、AnimationController自身でdispose() をして破棄されるべき。

みたいなことが書いてある。
Tickerとは、アニメーションフレームでコールバックを呼び出すために使われるものらしい。

つまり、
Stateful Widget内で作られたTickerを、super.dispose() を呼び出す前に全て明示的に破棄すれば良いっぽい。

解決策

Stateful Widgetクラス内に

  @override
  void  dispose() {
    <Controller1>.dispose();
    <Controller2>.dispose();   
    super.dispose();
  }

を追加してみると..

エラーが出なくなった!!!


この記事が気に入ったらサポートをしてみませんか?