Rules / Style / prefer-function-declarations-over-variables

prefer-function-declarations-over-variables

lint/style/prefer-function-declarations-over-variables
recommended
Same as prefer_function_declarations_over_variables · Dart lints

Flags a local variable bound to a function literal that should be a local function declaration.

Binding a closure to a variable (final f = () {...};) hides that it is a named function; a proper declaration (void f() {...}) reads more clearly, supports recursion and generic type parameters, and gives a return type a natural home. The rule only reports final or const local bindings, which provably can never be reassigned. A plain var f = () {...} is left alone, since proving it is never reassigned requires dataflow this syntax-only pass does not perform.

Invalid

example.dartdart
// Function literals bound to final/const locals should be declarations.
Future<void> g() async {}

void f() {
  final greet = () { print('hi'); };
  final add = (int a, int b) => a + b;
  final square = (int x) => x * x;
  final log = (String m) { print(m); };
  final wrap = () async { await g(); };
  final noop = () {};
  print(add(1, 2) + square(3) + greet.hashCode + log.hashCode + wrap.hashCode + noop.hashCode);
}
Use a function declaration to bind a function to a name.
4void f() {
5 final greet = () { print('hi'); };
Use a function declaration to bind a function to a name.
5 final greet = () { print('hi'); };
6 final add = (int a, int b) => a + b;
Use a function declaration to bind a function to a name.
6 final add = (int a, int b) => a + b;
7 final square = (int x) => x * x;
Use a function declaration to bind a function to a name.
7 final square = (int x) => x * x;
8 final log = (String m) { print(m); };
Use a function declaration to bind a function to a name.
8 final log = (String m) { print(m); };
9 final wrap = () async { await g(); };
Use a function declaration to bind a function to a name.
9 final wrap = () async { await g(); };
10 final noop = () {};

Valid

example.dartdart
// Proper local function declarations, and reassignable var bindings.
void f() {
  void greet() { print('hi'); }
  int add(int a, int b) => a + b;
  var handler = () => 1;
  handler = () => 2;
  final count = 3;
  final name = 'x';
  final list = <int>[];
  print(add(1, 2) + count + name.length + list.length + handler());
  greet();
}

How to configure

Set the severity of prefer-function-declarations-over-variables in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "prefer-function-declarations-over-variables": "error"
      }
    }
  }
}