prefer-expression-function-bodies

Same as prefer_expression_function_bodies in Dart lints

Path
lint/complexity/prefer-expression-function-bodies
Default
Off, opt in
Origin
Dart lints
Rule
352 of 512

Flags block function bodies that consist of a single return of a value.

A body like { return expr; } reads better as => expr. Every function body is checked: top-level functions, methods, getters, operators, local functions, and closures. Diagnostic ranges include an async/generator modifier.

int get width { return _width; } // flagged
int get width => _width;         // ok

Invalid

example.dartdart
int twiceOf(int x) {
  return x * 2;
}

class Box {
  int _value = 0;
  int get value {
    return _value;
  }

  int twice() {
    return _value * 2;
  }

  Box operator +(Box other) {
    return Box();
  }

  Future<int> load() async {
    return _value;
  }
}

void main() {
  int local(int x) {
    return x + 1;
  }

  final f = (int x) {
    return x;
  };
  print(local(f(1)));
}
Replace this block function body with an expression body.
1int twiceOf(int x) {
Replace this block function body with an expression body.
6 int _value = 0;
7 int get value {
Replace this block function body with an expression body.
10
11 int twice() {
Replace this block function body with an expression body.
14
15 Box operator +(Box other) {
Replace this block function body with an expression body.
18
19 Future<int> load() async {
Replace this block function body with an expression body.
24void main() {
25 int local(int x) {
Replace this block function body with an expression body.
28
29 final f = (int x) {

Valid

example.dartdart
int twiceOf(int x) => x * 2;

int clamp(int x) {
  if (x < 0) return 0;
  return x;
}

class Box {
  int _value = 0;
  int get value => _value;

  void reset() {
    return;
  }

  void bump() {
    _value++;
  }

  int compute() {
    final y = _value * 2;
    return y;
  }

  Iterable<int> values() sync* {
    yield _value;
  }
}

void main() {
  final f = (int x) {
    print(x);
  };
  f(1);
}

Configure prefer-expression-function-bodies

Set its severity in falcon.json. See the configuration guide.

falcon.jsonjson
{
  "linter": {
    "rules": {
      "complexity": {
        "prefer-expression-function-bodies": "error"
      }
    }
  }
}

Or silence one occurrence with a suppression comment; the reason is required.

example.dartdart
// falcon-ignore lint/complexity/prefer-expression-function-bodies: <reason>