الانتقال إلى المحتوى
تطبيقات الموبايلState Management· 7 دقائق للقراءة

No Magic in Provider or Bloc: InheritedWidget and How Rebuilds Reach Your Widget

Provider and Bloc reach your widgets through InheritedWidget and setState, so where you read the state decides what rebuilds.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • Flutter 3.x
محتويات المقال

A shop app's product page has an "Add to cart" button and a cart count in the app bar. Every tap rebuilds the whole page, image gallery and reviews included, and the team blames Provider and plans a move to Bloc. A quick experiment with context.watch<CartCubit>() in the same spot gives exactly the same rebuild counts. The packages aren't the problem. The line that reads the cart is at the top of the page's build().

The common misconception

The belief: state management packages run their own mechanism beside the widget tree. The store knows which widgets use which value and pushes updates straight to them, so it doesn't matter where you read the state, and switching packages changes what rebuilds.

It's a reasonable guess. The state really is outside the tree: a ChangeNotifier or a Bloc is a plain Dart object you can unit test without a widget in sight. The APIs look like subscriptions, watch, select, BlocBuilder, and each package has its own vocabulary, which suggests each has its own engine. The half-truth is that the state lives outside the tree. The path from that state to your pixels doesn't.

What actually happens

The state lives outside; the subscription lives in the tree

To reach a widget, the package places your object in an above your screen. Provider's README describes the package as "a wrapper around InheritedWidget to make them easier to use and more reusable." The Bloc docs say the same about theirs: flutter_bloc uses package:provider to implement BlocProvider and RepositoryProvider, and it re-exports Provider's watch, read and select extensions.

Looking it up registers a dependency

context.dependOnInheritedWidgetOfExactType<T>() returns the nearest T above that context and, in the docs' words, "registers this build context with the returned widget." When that widget changes, the context is rebuilt. The lookup is O(1): every element carries a table of the inherited widgets above it, so nothing walks up the . Its sibling getInheritedWidgetOfExactType returns the same widget without registering anything. That's the whole difference between Provider's context.watch and context.read.

Two ways an InheritedWidget notifies

The first is replacement. When the parent rebuilds the inherited widget with new data, Flutter calls updateShouldNotify(oldWidget). If it returns true, every dependent gets didChangeDependencies and a rebuild; if false, nobody does. The second is a notifier. InheritedNotifier listens to a Listenable and rebuilds its dependents when it fires, and the docs add that notifications between two frames are coalesced into one rebuild.

Provider and flutter_bloc follow the second pattern. In their source, the inherited element listens to your ChangeNotifier or your bloc's stream and, on a change, marks its dependents for a rebuild. BlocBuilder takes the other route: it's a StatefulWidget whose State subscribes to the stream and calls setState. Either way, an element is marked dirty and rebuilt in the next frame, exactly like your own setState.

The dependent is the context you pass

A is an element, one place in the tree. Call watch at the top of ProductScreen.build and the dependent is ProductScreen itself: its whole build() runs again and creates a new ProductDetails, which rebuilds too. Here is the mechanism without any package:

Dart cart_scope.dart
class CartScope extends InheritedNotifier<ValueNotifier<int>> {  const CartScope({super.key, required super.notifier, required super.child});  // Like context.watch: registers the caller as a dependent  static int countOf(BuildContext context) =>      context.dependOnInheritedWidgetOfExactType<CartScope>()!.notifier!.value;  // Like context.read: no dependency, so no rebuilds  static ValueNotifier<int> read(BuildContext context) =>      context.getInheritedWidgetOfExactType<CartScope>()!.notifier!;}
Dart product_screen.dart
class ProductScreen extends StatelessWidget {  const ProductScreen({super.key, required this.product});  final Product product;  @override  Widget build(BuildContext context) {    // Registers ProductScreen's element as the dependent    final count = context.watch<CartCubit>().state;    return Scaffold(      appBar: AppBar(actions: [Text('Cart: $count')]),      body: ProductDetails(product: product), // rebuilt on every change    );  }}

In a widget test that added three items, the first version built ProductScreen and ProductDetails four times each: the first build plus one per change. The second built each of them once, and only the BlocBuilder's builder ran four times. The wrong version written with Provider's context.watch<Cart>() or with CartScope.countOf gave identical counts, and a widget placed between the provider and the screen was built once in every run. Three changes inside a single frame caused one rebuild, as the InheritedNotifier docs promise.

What each API does underneath

You writeWhat Flutter does
context.watch<T>(), Provider.of<T>(context)Registers this context as a dependent of Provider's inherited widget
context.read<T>()Finds the same object without registering a dependency
context.selectRegisters a dependency and rebuilds only when the selected value changes
BlocProviderProvider's inherited widget, listening to the bloc's stream
BlocBuilder, ConsumerA small widget of their own that rebuilds alone: Consumer by depending, BlocBuilder with setState

How to apply it in your project

  1. Find reads at the top of big build methodsSearch for context.watch, Provider.of and .of(context) in screens. Each one makes that whole build() a dependent.
  2. Push the read down to the widget that shows itExtract a small widget, or wrap the part in BlocBuilder, Consumer or a Builder. The Bloc docs recommend BlocBuilder over context.watch to scope rebuilds explicitly.
  3. Narrow it when one field mattersUse context.select, BlocSelector or buildWhen when the widget needs one field of a larger state.
  4. Keep read for callbackscontext.read belongs in onPressed and similar handlers. Provider's README says it can't be called inside build.
  5. Count before and afterPut a debugPrint or a counter in the build() methods you suspect, trigger a change, and compare. The counts tell you which context depends, whatever package you use.

Key takeaways

  • Provider and Bloc reach widgets through InheritedWidget and setState; nothing bypasses the element tree.
  • The context you call watch or of with is the one that rebuilds, along with every new widget its build() creates.
  • read finds the same object without a dependency; watch and select register one.
  • Move reads down to the smallest widget that needs them, then narrow them with select or buildWhen.
  • Emit new objects: an in-place mutation looks like "no change" to every layer.

📚 المصادر

  1. InheritedWidget class — Flutter API
  2. BuildContext.dependOnInheritedWidgetOfExactType — Flutter API
  3. InheritedNotifier class — Flutter API
  4. provider package — pub.dev
  5. Flutter Bloc Concepts — Bloc library

التعليقات (0)