Skip to content

prefer_typedefs_for_callbacks

v1.0.0WarningConfigurableType Annotations

This rule flags an inline function type with two or more parameters, written where a typedef would name it.

void Function(String, int, bool) tells the reader the shape and nothing else — what the String is, what the bool means, and whether two such parameters are the same concept. A typedef gives the signature a name that can be reused, documented and searched for.

This rule is in the pedantic preset. min_parameters is the threshold at which reporting starts: at the default 2, a two-parameter inline type is already reported, while void Function() and void Function(String) are not. That is why Flutter ships VoidCallback and ValueChanged<T> for those shapes and stops there.

An event callback carried through a signature, spelled out inline at every hop:

void listen(void Function(String, int) onEvent) {}
class EventBus {
EventBus(this.onEvent);
final void Function(String, int) onEvent;
}

Name it once, then use the name:

typedef EventHandler = void Function(String name, int code);
void listen(EventHandler onEvent) {}
class EventBus {
EventBus(this.onEvent);
final EventHandler onEvent;
}

At the default min_parameters: 2, these are below the threshold and pass as written:

void onTap(void Function() callback) {}
void onChanged(void Function(String value) callback) {}

Declaring the typedef is the fix, so the function type inside it is never reported however many parameters it has:

typedef ProgressReport = void Function(int sent, int total, bool done);

With min_parameters: 1, a one-parameter inline type is reported as well:

many_lints.yaml
rules:
prefer_typedefs_for_callbacks:
min_parameters: 1
// Don't
void onChanged(void Function(String value) callback) {}
// Do
typedef TextChanged = void Function(String value);
void onChanged(TextChanged callback) {}

This rule is in the pedantic preset, so it is enabled by preset: pedantic or by name:

many_lints.yaml
rules:
prefer_typedefs_for_callbacks:
enabled: true
analysis_options.yaml
many_lints:
rules:
prefer_typedefs_for_callbacks:
min_parameters: 2
Option Type Default Description
min_parameters int 2 Fewest parameters an inline function type must have before it is reported. At 2, a two-parameter type is reported

To disable this rule:

many_lints.yaml
rules:
prefer_typedefs_for_callbacks: false

To keep the rule on but skip certain paths, use per-rule exclude.