Sub topic 3
Select only the state a widget needs
This chapter assumes you know Dart classes, StatefulWidget and setState, the provider package, and how to run a Flutter app in profile mode. A widget rebuilds when the state it depends on changes, so narrowing those dependencies reduces wasted work.
Select only the state a widget needs
A widget that reads a whole model rebuilds whenever any field changes. With provider, context.select subscribes the widget to one field only:
class UserName extends StatelessWidget {
const UserName({super.key});
@override
Widget build(BuildContext context) {
final name = context.select<UserModel, String>((user) => user.name);
return Text(name);
}
}This widget rebuilds only when user.name changes.
Avoid over-broad inherited widget dependencies
MediaQuery.of(context) depends on every field of MediaQueryData, including keyboard insets. Use the narrower accessor when you need one value:
final size = MediaQuery.sizeOf(context); // Flutter 3.10 and laterBuild long lists lazily and keep item identity stable
ListView.builder creates only the items near the viewport. A stable key lets Flutter match each element to its item when the list changes:
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return ProductTile(key: ValueKey(item.id), product: item);
},
)Keep build methods free of expensive work
build can run many times per second. Move sorting, parsing, and network calls out of build, into initialization, a cached value, or a provider. Keep build focused on describing the layout.
Rebuilds are not repaints: when RepaintBoundary helps
A rebuild recreates widget descriptions. A repaint redraws pixels. Wrapping a subtree in RepaintBoundary gives it its own layer, so a frequently repainting child, such as an animation, does not force its siblings to repaint. Add it only when profiling shows repaint cost.
A repeatable rebuild audit workflow
Measure, change one thing, and measure again. Set debugPrintRebuildDirtyWidgets to true to see which widgets rebuild each frame, then check frame times in Flutter DevTools in profile mode.
Exercise
A list item shows a count from a model with ten fields, and the item rebuilds whenever any field changes. How do you limit rebuilds to changes in the count?
Show answer
Use context.select to read only the count field, so the item rebuilds only when that field changes.