prefer-extracting-function-callbacks
Warns when an inline callback is passed as an argument to a function or method invocation.
Extracting long or complex callbacks can help with readability because all the callback logic is moved to a separate function declaration and replaced with just its name.
note
For this rule it's recommended to exclude the test
folder.
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).
Set ignored-invocations
(default is empty) to ignore function callbacks in specific invocations (example).
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-extracting-function-callbacks:
allowed-line-count: 3
ignored-named-arguments:
- onPressed
ignored-invocations:
- myInvocation
Example
❌ Bad:
void fn() {
// LINT: Prefer extracting this callback to a separate function or method.
listen(onPressed: () {
// Some
// Huge
// Callback
});
}
void listen({
void Function()? onPressed,
}) {}
✅ Good:
void fn() {
listen(onPressed: handlePressed);
}
void handlePressed() {
// Some
// Huge
// Callback
}
void listen({
void Function()? onPressed,
}) {}
Example with "allowed-line-count"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-extracting-function-callbacks:
allowed-line-count: 3
✅ Good:
void fn() {
// Correct, less than 3 lines
listen(() {
// No more than 3 lines
});
}
Example with "ignored-named-arguments"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-extracting-function-callbacks:
ignored-named-arguments:
- onPressed
✅ Good:
void fn() {
// Correct, 'onPressed' is ignored
listen(() {
// Some
// Huge
// Callback
});
}
Example with "ignored-invocations"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-extracting-function-callbacks:
ignored-invocations:
- listen
✅ Good:
void fn() {
// Correct, 'listen' is ignored
listen(() {
// Some
// Huge
// Callback
});
}