Rebuild your widget without setState — ValueNotifier!
Rebuilding UI is the most important concept that we will always need to use. But sometimes rebuilding your widget tree will be costlier! Let’s see how you can use ValueNotifier to rebuild the UI!
Flutter has been booming a lot for a few years now due to its flexibility, multi-platform support and of course, open-source! setState is the most common way that we use to rebuild our widget tree to reflect the changes. But, using setState to rebuild the widget tree can be costlier sometimes. Hence there are different state management concepts like provider, BLoC, GetX, etc. that are used to rebuild the UI.
One of the simplest ways is to use ValueNotifier! ValueNotifier creates a listener that will listen to the change in value for a particular variable. When the value is replaced with something that is not equal to the old value as evaluated by the equality operator, this class notifies its listeners.
We will be using ValueNotifier
and ValueListenableBuilder
in our code. Now, ValueNotifier
will help us to create a variable on which our app UI need to rebuild. So let’s say if we are re-creating the counter application, the counter
variable that holds the value will be declared now using ValueNotifier
. Syntax:
ValueNotifier<int> _counter;
This creates an object of ValueNotifier named _counter
that will hold or emit the value of type int!
On the other hand, ValueListenableBuilder
is used to rebuild our particular UI component. It takes 2 main parameters:
- valueListenable
- builder
valueListenable
will take the object of type ValueNotifier and hence it creates a listener on that variable. builder
takes up a widget that you need to rebuild. So in other words, valueListenable will listen to that change in the value of the ValueNotifier object and whenever it encounters a change, it rebuilds the widget provided into builder!
Now, to access the integer value from the ValueNotifier object, (here _counter), you can simply use the value parameter from it (_counter.value)!
Simple right? This will also save the cost of rebuilding the entire UI using setState!
Hope you enjoyed this article!
If you loved it, you can Buy Me A Coffee!
Don’t stop, until you are breathing!💙
- Abhishek Doshi