avoid_widget_returning_methods
Reports a method of a widget that returns a widget. Make that part a widget class of its own.
- Tier
- advisory
- Scope
- Flutter
- Fix
- none
What it reports
Section titled “What it reports”A method or a getter with a body, not static, such as Widget _buildHeader() { … } or Widget get _title => …, where:
- a widget class declares it: a class that extends Flutter’s
WidgetorState, or a mixin on one of them; - its declared return type is a widget:
Widget, a subtype such asTextorPreferredSizeWidget, orWidget?.
It does not report:
- the
buildmethod itself, and an override, with or without@override; - a method passed as a builder callback,
ListView.builder(itemBuilder: _buildItem): a callback has to be a function; - a function literal or a local function, such as
itemBuilder: (context, index) => …; - a static method, a top-level function, or a method of an extension;
- a method that returns something else, such as
List<Widget> _buildRows().
A method that a builder callback calls is reported like any other: in itemBuilder: (context, index) => _buildItem(index), _buildItem is reported.
What such a method returns becomes part of the widget whose build calls it: it is rebuilt with the whole on every setState, it cannot be const, and it shares the BuildContext of the widget around it. A widget class of its own is rebuilt only when what it is given changes. The rule is advisory: a helper method is not a defect by itself, and some are the better choice (see What it reports, in full).
Example
Section titled “Example”class _ProfileState extends State<Profile> { int _visits = 0;
@override Widget build(BuildContext context) => Column( children: [ _buildAvatar(), Text('$_visits visits'), ], );
Widget _buildAvatar() => CircleAvatar( radius: 32, backgroundImage: NetworkImage(widget.user.avatar), );}class _ProfileState extends State<Profile> { int _visits = 0;
@override Widget build(BuildContext context) => Column( children: [ _Avatar(address: widget.user.avatar), Text('$_visits visits'), ], );}
class _Avatar extends StatelessWidget { const _Avatar({required this.address});
final String address;
@override Widget build(BuildContext context) => CircleAvatar(radius: 32, backgroundImage: NetworkImage(address));}Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
assay: rules: avoid_widget_returning_methods: exclude: ["lib/legacy/**"]Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// The snack bar is shown from three handlers and built in one place.// ignore: assay/avoid_widget_returning_methods// ignore_for_file: assay/avoid_widget_returning_methods silences it in a whole file, and // ignore: avoid_widget_returning_methods without the prefix works too. See Suppressions.
Details
Section titled “Details”All cases
What it reports, in full
Section titled “What it reports, in full”A method or a getter with a body, not static, where:
- a widget class declares it: a class that extends Flutter’s
WidgetorState, or a mixin on one of them. AStatelessWidget, aStatefulWidget, aStateand a widget class of a package all count; - its declared return type is a widget:
Widget, a subtype such asText,AppBarorPreferredSizeWidget, or one of them made nullable,Widget?; - none of the exemptions below holds.
class _OrdersState extends State<Orders> { @override Widget build(BuildContext context) => Column(children: [_buildHeader(), _buildList()]);
// _buildHeader is reported Widget _buildHeader() => Text(widget.title);
// _buildList is reported Widget _buildList() => ListView(children: _rows);}It does not report:
- The
buildmethod itself. - An override, with or without
@override. It must keep the signature of the member it overrides:buildBodyof a base class of the project,buildPageorbuildTransitionsof a route. A method counts as one when its type inherits a member of the same name. - A method passed as a builder callback,
ListView.builder(itemBuilder: _buildItem)orBuilder(builder: _buildBody): a callback has to be a function. Every method the file names without calling it counts as one, also one assigned to a variable. - A function literal or a local function, such as
itemBuilder: (context, index) => …orWidget row(int index) => …inbuild. Neither is a method. - A static method.
static Widget create()is how a widget offers itself in a prepared form, such as wrapped in what provides its state. It is no part of the build of an instance. - A method with no body: an abstract one that subclasses fill in, or an
externalone. - A method that returns something else: a list of widgets,
List<Widget> _buildRows(), a future of a widget, a builder function, or no declared type at all. - A method of a class that is neither a widget nor a
State, a top-level function, or a method of an extension. - Anything in a package that does not use Flutter.
A method that a builder callback calls is reported like any other: in itemBuilder: (context, index) => _buildItem(index) the function literal is the callback, and _buildItem is a method that returns a widget.
It also reports a method that makes a widget for something other than a build, such as the SnackBar a handler hands to showSnackBar or the dialog it hands to showDialog; a method that only wraps what it is given, Widget _padded(Widget child) => Padding(padding: _inset, child: child);; a getter that hands out a widget it was given, Widget get child => _child;; and a public method that another file passes as a callback. Keep such a method with a justified suppression. A method written for subclasses to override is reported like any other, and only the overriding side is exempt: declare such a member abstract where you can.
What a widget-returning method costs
Section titled “What a widget-returning method costs”A method that returns a widget looks like a small widget and is none. What it returns becomes part of the widget whose build calls it, and that has three costs:
- It is rebuilt with the whole. Every
setStateof theState, and every rebuild from above, runs every such method again. A widget class of its own is rebuilt only when what it is given changes, and not at all when it isconst. - It cannot be const.
const _Header()is built once for the life of the program._buildHeader()cannot be. - It has no place of its own in the widget tree. It shares the
BuildContextof the widget around it, soTheme.of(context)and the like inside it subscribe the whole widget. A part that needs its own state, key or entry in the widget inspector cannot have one.
The reader pays too. A State with eight _build… methods is one class that does eight things and shares every field among them. Eight small widget classes say what each part needs in their constructors.
Such methods are the shortest way to break up a long build: no class, no constructor, every field in reach.