Observable Data
Instead of calling setState in a big widget, you can keep the data in an object that tells listeners when it changes. Only the small widgets that listen are rebuilt. Flutter has this in its core.
ValueNotifier: One Value
dart
final counter = ValueNotifier<int>(0);
// Anywhere in your app:
counter.value++;
// In the UI: rebuild only this part
ValueListenableBuilder<int>(
valueListenable: counter,
builder: (context, value, child) {
return Text('Count: $value');
},
)
Why is this good? Only the ValueListenableBuilder rebuilds when the value changes, not the entire page.
ChangeNotifier: Many Values and Methods
dart
class CartModel extends ChangeNotifier {
final List<String> _items = [];
List<String> get items => List.unmodifiable(_items);
int get count => _items.length;
void add(String item) {
_items.add(item);
notifyListeners(); // tell the UI
}
void remove(String item) {
_items.remove(item);
notifyListeners();
}
void clear() {
_items.clear();
notifyListeners();
}
}
dart
final cart = CartModel();
ListenableBuilder(
listenable: cart,
builder: (context, child) {
return Text('Items: ${cart.count}');
},
)
ElevatedButton(
onPressed: () => cart.add('Shoes'),
child: const Text('Add'),
)
| Tool | Holds | Listen with |
ValueNotifier<T> | One value | ValueListenableBuilder |
ChangeNotifier | A model with many fields | ListenableBuilder |
How Do Widgets Find the Model?
In the example above, cart is a global variable. That works for small apps, but it is hard to test. We need a way to provide the object to the widget tree. Flutter does it with an InheritedWidget.
InheritedWidget: Data That Flows Down
dart
class CartScope extends InheritedNotifier<CartModel> {
const CartScope({super.key, required CartModel cart, required super.child})
: super(notifier: cart);
static CartModel of(BuildContext context) {
final scope = context.dependOnInheritedWidgetOfExactType<CartScope>();
return scope!.notifier!;
}
}
// Provide it above your app:
CartScope(cart: CartModel(), child: const MyApp())
// Read it anywhere below:
final cart = CartScope.of(context);
Every widget below CartScope can find the cart and rebuilds automatically when it changes. Packages like Provider wrap this pattern so you do not have to write it yourself.
When to use what: Small apps and learning: ValueNotifier and ChangeNotifier. Bigger apps: a package such as Provider, Riverpod or Bloc, covered next.
Conclusion
ValueNotifier and ChangeNotifier give you reactive state without any package. InheritedWidget explains how Provider and Riverpod work under the hood.
Quick Summary: Use ValueNotifier for one value and ChangeNotifier for a model. Widgets listen and rebuild. InheritedWidget shares them down the tree.