Sub topic 5
Extract widget classes instead of helper methods
This chapter covers why a private method that returns a widget does not give you the same rebuild savings as a separate widget class. It assumes you know Dart classes, StatelessWidget and StatefulWidget, how setState triggers build, and what const constructors do. The earlier chapters on setState scope and const are the foundation here.
The problem with helper methods
Large build methods get long, so a common first move is to split them into methods:
import 'package:flutter/material.dart';
class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
int _likes = 0;
Widget _buildHeader() {
return const Padding(
padding: EdgeInsets.all(16),
child: Text('Profile', style: TextStyle(fontSize: 24)),
);
}
Widget _buildLikeRow() {
return Row(
children: [
Text('Likes: $_likes'),
IconButton(
icon: const Icon(Icons.favorite),
onPressed: () => setState(() => _likes++),
),
],
);
}
@override
Widget build(BuildContext context) {
return Column(
children: [
_buildHeader(),
_buildLikeRow(),
],
);
}
}This is easier to read than one long method. It does not change rebuild behavior at all. A method call is just Dart code that runs inside the parent's build. Each time setState runs, build runs, and both _buildHeader() and _buildLikeRow() run with it.
The framework never sees the methods. It only sees the widgets they return, as if you had written them inline. There is no element, no State object, and no place where Flutter can decide to skip work on behalf of _buildHeader.
What a widget class gives you
A widget class is a real node in the tree. When the parent rebuilds, Flutter walks to the child's element and calls Element.updateChild. That method compares the old widget with the new one. If both are the identical instance, Flutter skips the child and does not call its build. A const constructor is how you get an identical instance.
import 'package:flutter/material.dart';
class ProfileHeader extends StatelessWidget {
const ProfileHeader({super.key});
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.all(16),
child: Text('Profile', style: TextStyle(fontSize: 24)),
);
}
}
class LikeRow extends StatelessWidget {
const LikeRow({super.key, required this.likes, required this.onLike});
final int likes;
final VoidCallback onLike;
@override
Widget build(BuildContext context) {
return Row(
children: [
Text('Likes: $likes'),
IconButton(
icon: const Icon(Icons.favorite),
onPressed: onLike,
),
],
);
}
}
class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
int _likes = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
const ProfileHeader(),
LikeRow(
likes: _likes,
onLike: () => setState(() => _likes++),
),
],
);
}
}Now const ProfileHeader() is the same instance on every rebuild, so Flutter skips its subtree. LikeRow is not const because it receives changing values, so it rebuilds. That is correct, because its output changes.
How the framework decides
When a parent's build returns, Flutter reconciles each child slot. The check for each slot follows this order:
- If the new widget is identical to the old one (
identical(old, new)), the element keeps it and does not rebuild it, unless the element was marked dirty on its own. - If the types and keys match but the instances differ, Flutter updates the element with the new widget and rebuilds it.
- If the types or keys differ, Flutter discards the old element and creates a new one.
A helper method can only ever reach step 2 or 3 with whatever it returns. The only way it reaches step 1 is if the widget it returns is a const expression. The method call itself has no effect on this decision.
A second benefit: local state
A widget class can own state. A helper method cannot. If the like counter needs to change often, the cleanest fix is to make it a StatefulWidget so that setState rebuilds only that widget:
import 'package:flutter/material.dart';
class LikeCounter extends StatefulWidget {
const LikeCounter({super.key});
@override
State<LikeCounter> createState() => _LikeCounterState();
}
class _LikeCounterState extends State<LikeCounter> {
int _likes = 0;
@override
Widget build(BuildContext context) {
return Row(
children: [
Text('Likes: $_likes'),
IconButton(
icon: const Icon(Icons.favorite),
onPressed: () => setState(() => _likes++),
),
],
);
}
}The parent screen no longer holds _likes, so tapping the button never rebuilds the parent. This is the "push state down" pattern from the previous chapters, and extracting a class is what makes it possible.
Other reasons to prefer classes
Rebuild cost is the main reason, but not the only one:
- Keys and identity. A class can take a
key, so Flutter can track it when it moves in a list. A helper method result cannot carry identity beyond the keys you attach to the returned widget. - Hot reload and tooling. Widget classes show up by name in the Flutter Inspector and in
debugPrintRebuildDirtyWidgetsoutput. A helper method disappears into its parent, so you cannot tell which piece rebuilt. - Context. Each widget class gets its own
BuildContext. Calls such asTheme.of(context)orMediaQuery.sizeOf(context)then register a dependency on that small widget rather than on the whole screen, which keeps inherited-widget rebuilds narrow. - Testing. A widget class can be pumped in a widget test on its own.
Edge cases and gotchas
Helpers are fine when they do not depend on rebuild savings
A method that returns a widget is not wrong. If the subtree is cheap and always changes along with its parent, a method costs nothing extra. Methods are also fine for small pieces that exist only to name a block of code. Extract a class when the subtree is large, is static, has its own changing state, or needs its own context.
Static builder functions do not help either
Turning the method into a top-level or static function does not change the picture. It still runs inside the parent's build and returns a fresh widget on each call.
A non-const class can still rebuild needlessly
If you write ProfileHeader() without const, or pass a non-const argument such as a new list literal, a new instance is created every time. Flutter sees a different instance and calls build again. Look for the prefer_const_constructors and prefer_const_literals_to_create_immutables lint rules, which flag these cases.
Passing a closure creates a new instance each time
In the LikeRow example, onLike: () => setState(() => _likes++) is a new closure on each parent build. LikeRow already rebuilds because likes changes, so this costs nothing here. In a widget whose other fields are stable, a fresh closure alone still makes the instance different, and Flutter will rebuild it. Where this matters, define the callback as a method on the State class and pass onLike: _increment. Tear-offs of the same method compare equal, though the widget still has to be non-const to receive it.
Overriding `==` on widgets
You may see advice to override operator == on a widget so equal instances skip rebuilds. The Flutter documentation advises against this for widgets, because it makes comparison cost grow with the size of the widget's fields and can hide updates from the framework. Prefer const and smaller scopes.
Stateful classes cost more than stateless ones
Each StatefulWidget adds a State object. Do not turn every helper into a stateful widget. Use StatelessWidget unless the piece owns state.
Refactoring checklist
- Find methods in
buildthat return widgets, such as_buildHeader,_buildList, or_buildFooter. - Decide for each one whether it is static, has its own state, or is just a label for code.
- Move it into a
StatelessWidget(orStatefulWidgetif it owns state). Pass in only the values it needs asfinalfields. - Add a
constconstructor and useconstat each call site where all arguments are constant. - Run with
debugPrintRebuildDirtyWidgets = truebefore and after, and confirm the static class no longer appears in the output after asetState.
Quick comparison
| Aspect | Helper method | Widget class |
|---|---|---|
| Has its own element | No | Yes |
| Skipped when parent rebuilds | Only if it returns a `const` widget | Yes, when created with `const` and unchanged |
| Can hold state | No | Yes, as a `StatefulWidget` |
| Own `BuildContext` | No, uses the parent's | Yes |
| Visible by name in tools | No | Yes |
| Best for | Naming a small, cheap block | Large, static, or stateful subtrees |
Exercise
A screen's build method calls _buildBanner(), a method that returns const Text('Welcome') wrapped in a Padding, and setState runs on every tap elsewhere on the screen. A teammate says moving _buildBanner into its own StatelessWidget will cut rebuilds. Is that true? What must you do for the change to have an effect, and when would it have no effect?
Show answer
It helps only if the new class is created with const at the call site, for example const WelcomeBanner(). Then the instance is identical on every rebuild and Flutter skips its subtree, so build of the banner is not called. If the call site omits const, or passes a non-const argument, a new instance is created each time and the banner rebuilds anyway. Note that in this specific case the helper already returns a fully const widget, so the helper is already cheap: the method still runs, but it returns the same constant instance and Flutter skips that subtree. The extraction gains a named class, its own context, and better tooling output, but little extra rebuild saving.
Exercise
You extract PriceTag into a StatelessWidget but still see it listed by debugPrintRebuildDirtyWidgets on every parent setState. Name two likely causes and a fix for each.
Show answer
First, the call site is not const, so a new instance is created each time. Add const if all arguments are constants. Second, an argument changes identity on each build, such as a new list literal, a new closure, or a new object. Pass a stable value, use a method tear-off, or move the value into state so the instance can be reused. If the widget really depends on changing data, the rebuild is correct and the fix is to narrow the scope of the parent's setState instead.