Skip to content

prefer_explicit_function_type

v0.3.0 Warning Fix Type Annotations

Flags the bare Function type from dart:core — the one written with no return type and no parameter list.

Function accepts any number of arguments of any type and returns dynamic, so a call through it is unchecked. The compiler will not tell you that the callback you passed takes two arguments and you supplied one; you find out at runtime.

A callback field typed Function accepts anything, so the wrong callback compiles and the wrong call compiles with it:

class ConfirmDialog {
const ConfirmDialog({required this.onConfirm});
final Function onConfirm;
}
void show(ConfirmDialog dialog) {
// Compiles. Blows up at runtime if `onConfirm` takes no argument,
// or takes two, or takes a String.
dialog.onConfirm(42);
}

The same hole in a parameter, a return type and a collection:

void onEachRow(Function visit) {}
Function rowVisitor() => (int index) {};
final List<Function> validators = [];

Write the signature out. Every one of the mistakes above is now a compile error:

class ConfirmDialog {
const ConfirmDialog({required this.onConfirm});
final void Function(bool confirmed) onConfirm;
}
void show(ConfirmDialog dialog) {
dialog.onConfirm(true);
}
void onEachRow(void Function(int index) visit) {}
void Function(int index) rowVisitor() => (int index) {};
final List<bool Function(String value)> validators = [];

Anything that names the shape is fine — an inline function type, or a typedef:

typedef Validator = bool Function(String value);
final Validator notEmpty = (value) => value.isNotEmpty;
final int Function(String input) parse = int.parse;
final void Function() dismiss = () {};

The rule matches dart:core’s Function specifically, so a class of your own named Function is never reported.

See also: Dart language - Function type

This rule is in the recommended preset, so it is on with preset: recommended or preset: opinionated. Add it to preset: core with prefer_explicit_function_type: true.

To turn it off:

many_lints.yaml
rules:
prefer_explicit_function_type: false

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