Sub topic 2
Extract widget classes instead of helper methods
This chapter assumes you know Dart classes, StatelessWidget and StatefulWidget, setState, and how to run a Flutter app. It covers why a widget class can rebuild less than a helper method, how builder child parameters avoid rebuilding static parts, and how ValueListenableBuilder narrows a rebuild to one value.
Helper methods versus widget classes
A helper method returns a widget and runs inside its parent's build method. Each time the parent rebuilds, the helper body runs again. A widget class becomes its own element in the tree. If its constructor is const and the parent passes the same arguments, Flutter reuses the existing instance and skips its build.
// Helper method: runs every time the parent rebuilds.
Widget _buildHeader(String title) {
return Text(title, style: const TextStyle(fontSize: 24));
}
// Widget class: can be skipped when created with const.
class Header extends StatelessWidget {
const Header({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Text(title, style: const TextStyle(fontSize: 24));
}
}Use const Header(title: 'Inbox') in the parent's build method. The parent can still call setState, but Flutter does not rebuild Header unless its arguments change.
Cache static subtrees with the builder child parameter
Builder widgets such as AnimatedBuilder accept a child argument. Flutter builds that child once and passes it to the builder callback on every frame. The builder wraps the child in code that changes, so the static part is never rebuilt.
AnimatedBuilder(
animation: controller,
child: const Icon(Icons.refresh),
builder: (context, child) {
return RotationTransition(turns: controller, child: child);
},
)Rebuild only what changes with ValueListenableBuilder
ValueListenableBuilder listens to a ValueListenable, such as a ValueNotifier. When the value changes, only its builder runs. Pass the static parts through child.
final ValueNotifier<int> unread = ValueNotifier<int>(0);
ValueListenableBuilder<int>(
valueListenable: unread,
child: const Icon(Icons.mail),
builder: (context, count, child) {
return Row(children: [child!, Text('$count')]);
},
)Exercise
Exercise
A parent screen calls setState every second to update a clock. It also builds a Header with _buildHeader('Inbox'). How would you change this to stop the header from rebuilding each second?
Show answer
Replace _buildHeader with a Header widget class that has a const constructor, and create it in the parent with const Header(title: 'Inbox'). Flutter then reuses the header instance on each setState.