Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 73 ยท State management

Lifting State Up and ValueNotifier

Decide where Flutter state should live. Lift it up with callbacks, then use ValueNotifier, ValueListenableBuilder and ChangeNotifier to rebuild only what changed.

setState works well when one widget owns a piece of data. Trouble starts when two widgets that are not parent and child need the same data: a product list and a cart badge, a settings page and the whole app theme. Where should the data live, and how does the other widget find out it changed?

This lesson starts with Flutter's built-in answers: moving state to a common ancestor, then notifier objects (ValueNotifier, ChangeNotifier) that tell listeners when they change. These are the foundation of Provider, Riverpod and BLoC, which come next. It builds on StatefulWidget and setState.

Real vs stand-in. The Dart is real Flutter code, read-only here. The live examples are JavaScript stand-ins for the listener mechanism, which is the same observer pattern the framework uses.

Two kinds of state

Ephemeral Belongs to one widget. Use setState.
App state Shared by many screens. Needs a home.

Tab index and text focus are ephemeral. A cart is app state.

1 / 2

Ephemeral state versus app state

Ephemeral (local) state is only needed by one widget: which tab is selected, whether a checkbox is ticked, the current animation value. Keep it in a StatefulWidget. Do not reach for a library for these.

App state is shared across widgets or must survive navigation: the signed-in user, a shopping cart, the chosen theme, a list loaded from a server. There is no fixed rule for the split; if two distant widgets need it, or it must outlive a screen, treat it as app state.

Lifting state up

The simplest sharing technique: move the state to the closest common ancestor and pass values down as constructor arguments and changes up as callbacks. This is "data down, events up".

DART
class ShopPage extends StatefulWidget {
  const ShopPage({super.key});

  @override
  State<ShopPage> createState() => _ShopPageState();
}

class _ShopPageState extends State<ShopPage> {
  final List<String> _cart = [];

  void _add(String item) => setState(() => _cart.add(item));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [CartBadge(count: _cart.length)],   // data down
      ),
      body: ProductList(onAdd: _add),                // events up
    );
  }
}

class ProductList extends StatelessWidget {
  const ProductList({super.key, required this.onAdd});

  final void Function(String item) onAdd;

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        for (final name in const ['Tea', 'Coffee', 'Cocoa'])
          ListTile(title: Text(name), onTap: () => onAdd(name)),
      ],
    );
  }
}

ProductList and CartBadge never know about each other. The parent owns the list, so when setState runs, both are rebuilt with fresh values. The weakness: if CartBadge is five levels down, every widget in between must accept and forward the data ("prop drilling"), and the whole ShopPage rebuilds on every change.

ValueNotifier and ValueListenableBuilder

A ValueNotifier<T> holds one value and notifies listeners when you assign a different one. ValueListenableBuilder listens and rebuilds only its own subtree.

DART
class CounterScreen extends StatefulWidget {
  const CounterScreen({super.key});

  @override
  State<CounterScreen> createState() => _CounterScreenState();
}

class _CounterScreenState extends State<CounterScreen> {
  final _count = ValueNotifier<int>(0);

  @override
  void dispose() {
    _count.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const Text('This label never rebuilds'),
        ValueListenableBuilder<int>(
          valueListenable: _count,
          builder: (context, value, child) => Text('Count: $value'),
        ),
        FilledButton(
          onPressed: () => _count.value++,
          child: const Text('Add'),
        ),
      ],
    );
  }
}

No setState is called. Setting _count.value runs the setter, which compares the new value with the old (!=), and if different calls notifyListeners(). The builder re-runs only its closure. The optional child parameter lets you pass a subtree that does not depend on the value so it is built once.

Two details matter:

  • The comparison uses ==. If the value is a mutable list and you add to it, the object is the same, so nothing is notified. Assign a new list: items.value = [...items.value, newItem].
  • The notifier must be disposed by whoever created it.

Stand-in: how a notifier works

This is a faithful miniature of ChangeNotifier and ValueNotifier: a listener set and a setter that skips equal values.

JS A ValueNotifier in 25 lines

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice what the mutation case teaches: a notifier detects assignment of a different value, not changes inside an object.

ChangeNotifier for richer models

When state has several fields and methods, make your own class that extends ChangeNotifier and call notifyListeners() after each change:

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();
  }

  void clear() {
    if (_items.isEmpty) return;
    _items.clear();
    notifyListeners();
  }
}

The model exposes read-only views and changes only through methods, so every change is followed by a notification. Widgets listen with ListenableBuilder:

DART
ListenableBuilder(
  listenable: cart,
  builder: (context, child) => Text('Items: ${cart.count}'),
)

ListenableBuilder accepts any Listenable, including a ChangeNotifier, a ValueNotifier, an AnimationController, or a Listenable.merge([a, b]) to listen to several at once. AnimatedBuilder is the same idea with an animation-flavored name.

But who holds the CartModel so that distant widgets can reach it? You can pass it through constructors (prop drilling again), put it in a global variable (hard to test), or provide it through an InheritedWidget (BuildContext and InheritedWidget). That last option is exactly what Provider packages up in State management with Provider.

Stand-in: a model with several listeners

JS A cart model and two independent listeners

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The badge and the list know nothing about each other or about the button that changed the cart. They only know the model.

Choosing between the options

Situation Reach for
One widget's own data StatefulWidget + setState
Parent and a few children Lift state up, pass callbacks
One value, rebuild a small part ValueNotifier + ValueListenableBuilder
A model with several fields and actions ChangeNotifier + ListenableBuilder
Many screens, testing, async data Provider, Riverpod or BLoC

Never forget dispose for notifiers you create, and remove listeners you add with addListener.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is an example of ephemeral state?

    A selected tab belongs to one widget and can use setState. The others are shared app state.
  2. 2. You call items.value.add(x) on a ValueNotifier<List<int>>. What happens?

    ValueNotifier notifies when a different value is assigned. Mutating the list inside it does not assign. Assign a new list instead.
  3. 3. What does ValueListenableBuilder rebuild?

    It listens to the notifier and calls its builder, so only that subtree is rebuilt.
  4. 4. Which method must a ChangeNotifier subclass call after changing its data?

    notifyListeners tells every registered listener (for example a ListenableBuilder) that the data changed.

Summary

  • Keep data local with setState until two unrelated widgets need it.
  • Lifting state up means "data down, events up"; it can cause prop drilling and wide rebuilds.
  • ValueNotifier + ValueListenableBuilder rebuild only the part that depends on one value; assign a new object to trigger it.
  • ChangeNotifier models have fields, methods and notifyListeners(); ListenableBuilder listens to them.
  • Dispose notifiers you create. State libraries build on these ideas.

Next: State Management with Provider