Saltar al contenido principal

prefer-extracting-callbacks

added in: 1.0.0 style

Warns about inline callbacks in a widget tree and suggests to extract them to widget methods in order to make a build method more readable. In addition extracting can help test those methods separately as well.

info

This rule will not trigger on:

  • arrow functions like onPressed: () => _handler(...) in order to cover cases when a callback needs a variable from the outside;
  • empty blocks.
  • Flutter specific: arguments with functions returning Widget type (or its subclass) and with first parameter of type BuildContext. "Builder" functions is a common pattern in Flutter, for example, IndexedWidgetBuilder typedef is used in ListView.builder.:::

Config

Set allowed-line-count (default is none) to configure the maximum number of lines after which the rule should trigger.

Set ignored-named-arguments (default is none) to ignore specific named parameters.

dart_code_linter:
...
rules:
...
- prefer-extracting-callbacks:
ignored-named-arguments:
- onPressed
allowed-line-count: 3

Example

Bad:

class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return TextButton(
style: ...,
onPressed: () { // LINT
// Some
// Huge
// Callback
},
child: ...
);
}
}

Good:

class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return TextButton(
style: ...,
onPressed: () => handlePressed(context),
child: ...
);
}

void handlePressed(BuildContext context) {
...
}
}

class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return TextButton(
style: ...,
onPressed: handlePressed,
child: ...
);
}

void handlePressed() {
...
}
}