Skip to content

prefer_void_callback

v0.4.0 Warning Fix Type Annotations

Flags uses of void Function() that can be replaced with the VoidCallback typedef from dart:ui. The typedef is shorter, more readable, and is the standard Flutter convention for no-argument void callbacks.

VoidCallback is a well-known typedef in the Flutter framework. Using it instead of the verbose void Function() makes code more concise and consistent with the rest of the Flutter ecosystem. The quick fix automatically replaces the type and adds the necessary import.

See also: VoidCallback typedef

class BadWidget {
final void Function() onTap;
final void Function()? onLongPress;
const BadWidget(this.onTap, this.onLongPress);
}
void badParameter(void Function() callback) {}
void Function() badReturnType() => () {};
List<void Function()> callbacks = [];
class GoodWidget {
final VoidCallback onTap;
final VoidCallback? onLongPress;
const GoodWidget(this.onTap, this.onLongPress);
}
// Function types with parameters or different return types are fine:
void goodWithParams(void Function(int value) callback) {}
int Function() goodIntReturn = () => 0;
Future<void> Function() goodFutureReturn = () async {};

This rule is in the opinionated preset, so it is on with preset: opinionated, or by name:

many_lints.yaml
rules:
prefer_void_callback: true

To turn it off again:

many_lints.yaml
rules:
prefer_void_callback: false

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