ValueNotifier: Notifies on Replacement, Not Mutation
ValueNotifier is a simple state holder that tells widgets to rebuild when its single value is replaced. It's great for immutable data like a boolean toggle or counter.
WHY IT EXISTS Flutter needs a simple, built-in way to broadcast changes for a single piece of state without forcing developers into a complex state management library. ValueNotifier is the lightweight tool for this common problem: managing one value and telling others when it changes.
THE MENTAL MODEL A ValueNotifier is a box with a loudspeaker. The box holds a single value. The loudspeaker only goes off when you take the old value out and put a completely new one in. If you just reach in and tweak the value that's already there (like adding an item to a list), the loudspeaker stays silent because the box still contains the same list object.
HOW IT WORKS ValueNotifier wraps a single value. When you assign a new object to its .value property, it compares the new value with the old one using the standard == equality operator. If they are not equal, it automatically calls notifyListeners(). Any widget or object that has registered a listener (e.g., via a ValueListenableBuilder) will then be alerted to the change, typically triggering a UI rebuild.
WHEN TO USE IT Use ValueNotifier for simple, local state that doesn't warrant a heavy solution. It is perfect for immutable data types like integers, booleans, strings, or your own custom immutable classes. A classic use case is managing the state of a single counter (ValueNotifier<int>) or a theme toggle (ValueNotifier<bool>).
WHEN NOT TO USE IT Avoid ValueNotifier with mutable objects like List or Map if you plan to modify them in-place. It will not notify listeners on mutations like myListNotifier.value.add(5) because the list object reference itself has not changed. For these scenarios, either create a new copy of the list on each change or extend ChangeNotifier directly and call notifyListeners() manually after mutations.
ONE CANONICAL EXAMPLE A ValueNotifier<int> for a simple counter works perfectly. When you increment, you assign counter.value = counter.value + 1. This replaces the old integer object with a new one, which correctly triggers a notification. In contrast, if you have a ValueNotifier<List<int>> and call myListNotifier.value.add(10), no notification will be sent because the list object itself is the same, even though its contents changed.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.