
No Magic in Provider or Bloc: InheritedWidget and How Rebuilds Reach Your Widget
- كاتب موثّق
- Flutter 3.x
محتويات المقال
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
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
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
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.
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
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:
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!;}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 ); }}class ProductScreen extends StatelessWidget { const ProductScreen({super.key, required this.product}); final Product product; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(actions: [ // BlocBuilder's own State listens and calls setState BlocBuilder<CartCubit, int>( builder: (context, count) => Text('Cart: $count'), ), ]), body: ProductDetails(product: product), // built once ); }}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
context.watch<T>(), Provider.of<T>(context) | |
context.read<T>() | |
context.select | |
BlocProvider | |
BlocBuilder, Consumer | Consumer by depending, BlocBuilder with setState |
How to apply it in your project
Find reads at the top of big build methods Search for context.watch,Provider.ofand.of(context)in screens. Each one makes that wholebuild()a dependent.Push the read down to the widget that shows it Extract a small widget, or wrap the part in BlocBuilder,Consumeror aBuilder. The Bloc docs recommendBlocBuilderovercontext.watchto scope rebuilds explicitly.Narrow it when one field matters Use context.select,BlocSelectororbuildWhenwhen the widget needs one field of a larger state.Keep read for callbacks context.readbelongs inonPressedand similar handlers. Provider's README says it can't be called insidebuild.Count before and after Put a debugPrintor a counter in thebuild()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 InheritedWidgetandsetState; nothing bypasses the element tree.The context you call watchorofwith is the one that rebuilds, along with every new widget itsbuild()creates.readfinds the same object without a dependency;watchandselectregister one.Move reads down to the smallest widget that needs them, then narrow them with selectorbuildWhen.Emit new objects: an in-place mutation looks like "no change" to every layer.
التعليقات (0)