== Why is this an issue?

`forEach` function in Dart allows to iterate over collection and do some actions with their elements. This is convenient and more concise if you can pass the reference to the action directly through argument. For example this code:

[source,dart]
----
void actOnList(List<String> list, Function(String) action) {
  list.forEach(action);
}
----

looks more concise than this code:

[source,dart]
----
void actOnList(List<String> list, Function(String) action) {
  for(String s in list) {
    action(s);
  }
}
----

However, if you want to have a function literal as `forEach` argument, you might face some limitations:

* If you place `return` in the function literal, it will only return the value for that iteration, while you might want to return from the function.
* The bode of the function literal can't contain `await`, while ordinary `for` loop can contain it.

As a consequence, if you want to use `forEach` with a function literal as an argument, it's better to use a simple `for` loop instead.

== How to fix it

Replace the `forEach` with a `for` loop or use reference to a function instead of function literal.

=== Code examples

==== Noncompliant code example

[source,dart,diff-id=1,diff-type=noncompliant]
----
void f1(List<String> list) {
  list.forEach((s) => print(s));
}
----

==== Compliant solution

[source,dart,diff-id=1,diff-type=compliant]
----
void f1(List<String> list) {
  list.forEach(print);
}
----

==== Noncompliant code example

[source,dart,diff-id=2,diff-type=noncompliant]
----
void f2(List<String> list) {
  list.forEach((s) {
    if (s.length > 5) {
      print("foo");
    } else {
      print("bar");
    }
  });
}
----

==== Compliant solution

[source,dart,diff-id=2,diff-type=compliant]
----
void f2(List<String> list) {
  for(String s in list) {
    if (s.length > 5) {
      print("foo");
    } else {
      print("bar");
    }
  }
}
----


== Resources

=== Documentation

* Dart Docs - https://dart.dev/tools/linter-rules/avoid_function_literals_in_foreach_calls[Dart Linter rule - avoid_function_literals_in_foreach_calls]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

* Function literals shouldn't be passed to 'forEach'.

=== Highlighting

`forEach` function

'''
== Comments And Links
(visible only on this page)

endif::env-github,rspecator-view[]
