avoid-function-literals-in-foreach-calls

Same as avoid_function_literals_in_foreach_calls in Dart lints

Path
lint/complexity/avoid-function-literals-in-foreach-calls
Default
Off, opt in
Origin
Dart lints
Rule
66 of 512

Flags a function literal passed to an Iterable's forEach.

A for-in loop reads more clearly than forEach with a closure, and unlike the closure it can await, break, and continue. Stream and Map receivers, tear-offs, null-aware chains, and receivers reached through method calls are left alone, matching the SDK lint.

Invalid

example.dartdart
void bad(List<int> items, List<int> list, List<int> names, List<int> values,
    List<int> data, void Function(int) save, void Function(int) sink,
    void Function(int) process, void Function(int) log) {
  items.forEach((e) { print(e); });
  list.forEach((x) => print(x));
  names.forEach((name) { save(name); });
  values.forEach((v) => sink(v));
  data.forEach((item) { process(item); log(item); });
}
Avoid using a function literal in a `forEach` call; use a for-in loop instead.
3 void Function(int) process, void Function(int) log) {
4 items.forEach((e) { print(e); });
Avoid using a function literal in a `forEach` call; use a for-in loop instead.
4 items.forEach((e) { print(e); });
5 list.forEach((x) => print(x));
Avoid using a function literal in a `forEach` call; use a for-in loop instead.
5 list.forEach((x) => print(x));
6 names.forEach((name) { save(name); });
Avoid using a function literal in a `forEach` call; use a for-in loop instead.
6 names.forEach((name) { save(name); });
7 values.forEach((v) => sink(v));
Avoid using a function literal in a `forEach` call; use a for-in loop instead.
7 values.forEach((v) => sink(v));
8 data.forEach((item) { process(item); log(item); });

Valid

example.dartdart
void good(List<int> items, List<int>? list, Map<int, int> map, List<int> numbers) {
  items.forEach(print);
  list?.forEach((e) => print(e));
  map.forEach((k, v) => print('$k$v'));
  for (final e in items) {
    print(e);
  }
  numbers.map((e) => e * 2);
}

Configure avoid-function-literals-in-foreach-calls

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

falcon.jsonjson
{
  "linter": {
    "rules": {
      "complexity": {
        "avoid-function-literals-in-foreach-calls": "error"
      }
    }
  }
}

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

example.dartdart
// falcon-ignore lint/complexity/avoid-function-literals-in-foreach-calls: <reason>