1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Riverpod Generator TIPs / Stateの再ビルド時に現在のStateを考慮してビルドする

Posted at

次の SomeIntValue は別の OtherIntValue の状態に依存しているため、OtherIntValue の状態が変わるたびに SomeIntValue のStateの再ビルドが行われます。

some_int_value.dart
@riverpod
class SomeIntValue extends _$SomeIntValue {
  @override
  int build() {
    final otherIntValue = ref.watch(otherIntValueProvider);
    // ビルド処理
    ...
  }
}

この再ビルド時に SomeIntValue の現在のStateをもとに新しい状態を作りたい場合は stateOrNull を使うと良さそうです。stateOrNull は初回のビルド時には null、再ビルド時は現在の state が得られます。

some_int_value.dart
@riverpod
class SomeIntValue extends _$SomeIntValue {
  @override
  int build() {
    final otherIntValue = ref.watch(otherIntValueProvider);
    return (stateOrNull ?? 0) + otherIntValue;
  }
}
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?