LoginSignup
5
0

More than 1 year has passed since last update.

riverpodでautoDiposeのStateNotifierを使用する時の注意点

Posted at

問題

autoDisposeStateNotifierProviderを作って、
widgetから呼び出そうとした時、以下のエラーが発生。

Bad state: Tried to use StateNotifier after dispose was called

原因

autoDisposeをつけたproviderは初めて呼び出されたwidgetから生存開始し、
subWidgetも含め、stateを監視されている間は生き続ける。
その初回widgetが破棄されると同時にdisposeされる。それがautoの意味らしい。

ただ、どのwidgetからも監視されず、例えば毎回ref.readで呼び出されると、その都度disposeされてしまう。たぶん、riverpodでは、Stateを保持する必要性をlistenerがいるかで判断している。

解決方法

適切のところでref.watchをする。

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0