My Flutter Riverpod State Notifier maintains an array of more than 10000 large objects. One of the properties of the object is a boolean flag isFavorite
. The flag toggles value when the user clicks a button.
Now, should I necessarily make a clone of the entire object array in order to trigger a state change notification? This seems to be wasteful of resources when only a single bit has changed. Is there a more efficient way to just change the flag in one object and force Riverpod to take notice?
Is there a Riverpod-equivalent of setState()
in Stateful Widgets ?
2
Answers
You can use
useState
from flutter_hooks package. The Riverpod documentation suggests to AVOID using providers for local widget state, and mentioned flutter_hooks as one solution to be considered.You can then replace flutter_riverpod package with hooks_riverpod, and use the hooks inside
HookConsumerWidget
which allows you to use both hooks and Riverpod.More about Riverpod+hooks: https://riverpod.dev/docs/concepts/about_hooks
You can override
updateShouldNotify
in yourNotifier
subclass to use equality rather than identity, and ensure that your state has a valid equality (overridden==
andhashCode
). Then, you will never need to copy your state, just be sure to callref.notifyListeners
for any possible mutations.