Skip to main content

prefer-extracting-callbacks

added in: 1.6.0
⚙️
Pro+

Warns about inline callbacks in a widget tree and suggests to extract them to widget methods in order to make the build method more readable.

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.
note

You can fix this rule's issues using the "Extract Method" assist.

⚙️ Config

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

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

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-extracting-callbacks:
allowed-line-count: 3
ignored-named-arguments:
- onPressed

Example

❌ Bad:

class MyWidget extends StatelessWidget {

Widget build(BuildContext context) {
return TextButton(
style: ...,
// LINT: Prefer extracting the callback to a separate widget method.
onPressed: () {
// Some
// Huge
// Callback
},
child: ...
);
}
}

✅ Good:

class MyWidget extends StatelessWidget {

Widget build(BuildContext context) {
return TextButton(
style: ...,
onPressed: () => handlePressed(context),
child: ...
);
}

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

class MyWidget extends StatelessWidget {

Widget build(BuildContext context) {
return TextButton(
style: ...,
onPressed: handlePressed,
child: ...
);
}

void handlePressed() {
...
}
}

Example with "allowed-line-count"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-extracting-callbacks:
allowed-line-count: 3

✅ Good:

class MyWidget extends StatelessWidget {

Widget build(BuildContext context) {
return TextButton(
style: ...,
// Correct, less than 3 lines
onPressed: () {
// No more than 3 lines
},
child: ...
);
}
}

Example with "ignored-named-arguments"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-extracting-callbacks:
ignored-named-arguments:
- onPressed

✅ Good:

class MyWidget extends StatelessWidget {

Widget build(BuildContext context) {
return TextButton(
style: ...,
// Correct, 'onPressed' is ignored
onPressed: () {
// Some
// Huge
// Callback
},
child: ...
);
}
}