In Flutter, reactive UI is key to building efficient and modern applications. While complex state management solutions like Provider, Riverpod, or Bloc exist, Flutter also offers lightweight tools for managing local state updates. Among these, ValueNotifier
and ValueListenableBuilder
are simple yet powerful.
This tutorial explores these two classes with practical examples to help you integrate them into your Flutter projects confidently.
What is ValueNotifier
?
ValueNotifier<T>
is a special class that extends ChangeNotifier
and holds a single value. When its value changes, all listeners are notified.
ValueNotifier<int> counter = ValueNotifier<int>(0);
You can update the value like this:
counter.value++;
When the value is updated, any widgets listening to it will rebuild if implemented correctly.
What is ValueListenableBuilder
?
ValueListenableBuilder
is a widget that rebuilds itself when the ValueNotifier
it listens to changes. This makes it perfect for small local updates like counters, toggles, or form validation feedback.
Here’s how you might use it with our counter:
</pre> ValueNotifier<int> counter = ValueNotifier<int>(0); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('ValueNotifier Example')), body: Center( child: ValueListenableBuilder<int>( valueListenable: counter, builder: (context, value, child) { return Text('Counter: $value', style: TextStyle(fontSize: 24)); }, ), ), floatingActionButton: FloatingActionButton( onPressed: () => counter.value++, child: Icon(Icons.add), ), ); } <pre>
When to Use ValueNotifier
-
When working with simple state that doesn’t need global access.
-
For counters, toggles, booleans, or single-field validation.
-
Inside custom widgets or internal logic layers.
Pros and Cons
Pros:
-
Lightweight.
-
No dependencies.
-
Ideal for widget-specific logic.
Cons:
-
Not suitable for large-scale or app-wide state.
-
Manual disposal may be required in some cases.
Disposal Tips
If you’re using a ValueNotifier
inside a StatefulWidget
, don’t forget to dispose of it to avoid memory leaks:
@override void dispose() { counter.dispose(); super.dispose(); }
Final Thoughts
ValueNotifier
and ValueListenableBuilder
offer a concise and efficient way to manage reactive updates in Flutter. When your app doesn’t require a full-fledged state management system, they can keep your code clean and straightforward.
Consider them as your first tool of choice when dealing with UI components that need local and simple state.