Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 73 ยท State management

State Management with Provider

Use the Provider package in Flutter: ChangeNotifierProvider, context.watch, read and select, control rebuild scope, and avoid the classic pitfalls.

In the previous lesson you made a ChangeNotifier model, but you still needed a way for distant widgets to reach it. Provider is a small package that solves exactly that. It puts an object high in the widget tree and lets any widget below look it up and, if you want, rebuild when it changes.

Provider is a thin, friendly wrapper around InheritedWidget (BuildContext and InheritedWidget) and ChangeNotifier. It has been the most common first state solution in Flutter, and its ideas (scoped objects, watch versus read) carry over to Riverpod and BLoC.

Real vs stand-in. Provider is a package that cannot run on this site, so the Dart is read-only. The JavaScript examples are stand-ins: a tiny provider scope with a notifier, showing which "widgets" rebuild for watch, read and select.

Provider in three steps

Provide Put a model above the widgets.
Consume Find it from any child.
Rebuild Only listeners redraw.
1 / 2

Setup

Add the package in pubspec.yaml (use whatever the current version is):

YAML
dependencies:
  flutter:
    sdk: flutter
  provider: ^6.1.0

Then run flutter pub get.

Providing a model

Reuse a ChangeNotifier:

DART
class CartModel extends ChangeNotifier {
  final List<Product> _items = [];

  List<Product> get items => List.unmodifiable(_items);
  int get count => _items.length;
  double get total => _items.fold(0, (sum, p) => sum + p.price);

  void add(Product product) {
    _items.add(product);
    notifyListeners();
  }

  void remove(Product product) {
    _items.remove(product);
    notifyListeners();
  }
}

Provide it above every widget that needs it, usually around MaterialApp:

DART
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => CartModel(),
      child: const ShopApp(),
    ),
  );
}

ChangeNotifierProvider creates the model lazily (the first time something asks for it), keeps it alive, and disposes it when the provider leaves the tree. For several models use MultiProvider(providers: [...], child: ...).

Reading: watch, read and select

Provider adds extension methods on BuildContext:

DART
class CartBadge extends StatelessWidget {
  const CartBadge({super.key});

  @override
  Widget build(BuildContext context) {
    final count = context.watch<CartModel>().count;   // rebuilds on change
    return Badge(label: Text('$count'), child: const Icon(Icons.shopping_cart));
  }
}

class AddButton extends StatelessWidget {
  const AddButton({super.key, required this.product});
  final Product product;

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.add),
      onPressed: () => context.read<CartModel>().add(product),  // no rebuild
    );
  }
}

The rules:

  • context.watch<T>() subscribes this widget to T. Whenever notifyListeners runs, the widget rebuilds. Use it in build.
  • context.read<T>() gets the object without subscribing. Use it in callbacks such as onPressed. Calling read in build means "I want this once", which is usually a bug if the data changes.
  • context.select<T, R>((t) => ...) subscribes to one derived value and rebuilds only when that value changes (compared with ==).
DART
// Rebuilds only when the number of items changes, not when prices change.
final count = context.select<CartModel, int>((cart) => cart.count);

Do not call watch or select inside callbacks or initState; they only work during build.

Consumer when you want a smaller rebuild

context.watch rebuilds the whole widget it is called in. If only a small part needs the data, wrap that part in a Consumer:

DART
Scaffold(
  appBar: AppBar(title: const Text('Shop')),
  body: Column(
    children: [
      const ProductGrid(),           // not rebuilt by cart changes
      Consumer<CartModel>(
        builder: (context, cart, child) => Text('Total: \$${cart.total}'),
      ),
    ],
  ),
)

Consumer also gives a child parameter for a subtree that should not rebuild, just like ValueListenableBuilder.

Stand-in: watch, read and select

This miniature provides a notifier and counts how often three "widgets" rebuild after a few changes.

JS Which widgets rebuild? watch vs read vs select

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

No output.

The watching widget rebuilt four times, the reading widget only at mount, and the select widget twice (only when the count changed). Choosing select over watch is the first performance tool Provider gives you.

Other provider types

  • Provider<T>: provides a plain object that never notifies (a repository, a config).
  • ProxyProvider: builds an object from other providers (a Repository that needs an ApiClient).
  • FutureProvider / StreamProvider: expose async values.
  • ChangeNotifierProvider.value: provide an existing instance. Use it only when the instance is created elsewhere, never with create for a new object.
DART
MultiProvider(
  providers: [
    Provider(create: (_) => ApiClient()),
    ProxyProvider<ApiClient, ProductRepository>(
      update: (_, api, __) => ProductRepository(api),
    ),
    ChangeNotifierProvider(create: (_) => CartModel()),
  ],
  child: const ShopApp(),
)

Pitfalls

  • Provider not found. ProviderNotFoundException means the widget is not below the provider. Providers added inside a route are not visible to other routes, because each route is a sibling subtree under Navigator. Provide at the app root or above the navigator when several screens share a model.
  • Provider type mismatch. You must ask for the exact type you provided: context.read<CartModel>(), not a supertype. Declare the generic explicitly.
  • Forgetting notifyListeners. The model changes but nothing redraws.
  • Notifying during build. Changing a model while a widget is building causes the "setState() called during build" error. Trigger changes from callbacks or after the first frame.
  • Mutating exposed lists. Return List.unmodifiable(_items) so only methods change state.
  • create that does heavy work. Models are created lazily on first read; keep constructors cheap and load data in a method.
  • Using watch in a huge build. Rebuilds the whole screen. Use select or Consumer.

When Provider is enough

Provider has no magic: you still manage async loading, errors and testing by hand, and the lookup is by type at runtime (a missing provider is an error at runtime, not compile time). That is acceptable for many apps. When you want compile-time safety, async states and easy overrides in tests, look at Riverpod.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should you use context.read<CartModel>()?

    read gets the object without subscribing, which is right for event handlers.
  2. 2. What is the difference between watch and select?

    select compares the derived value with its previous one and skips rebuilds when it is equal.
  3. 3. You get ProviderNotFoundException on a second screen. A likely cause?

    Routes are sibling subtrees. A provider created inside one route is invisible to others, so provide it higher up.
  4. 4. What does ChangeNotifierProvider do when it leaves the widget tree?

    A provider that created the model with create also disposes it, so you do not leak listeners.

Summary

  • Provider puts objects in the widget tree so any descendant can find them by type.
  • ChangeNotifierProvider creates, shares and disposes a ChangeNotifier.
  • watch subscribes in build, read is for callbacks, select rebuilds only when one derived value changes; Consumer narrows the rebuilt area.
  • Provide above every consumer (usually above MaterialApp), never notify during build, and expose unmodifiable data.
  • Provider relies on runtime lookups; Riverpod removes that limitation.

Next: Riverpod