In iterable.dart file, code for forEach is:

void forEach(void f(E element)) {
  for (E element in this) f(element);
}

You can see, forEach parameter accepts a method and its return type should be void but following code just works fine without any error:

var list = [1, 2, 3];
list.forEach((item) {
  print(item);
  return true; // should show an error
});


Solution 1: josef atef

I think in dart when you use the void return type with a function , the return type could be void or anything else for example :

main()=>print(function() as int); // the output is 12
void function()=>12; 

in this example the void function returns a value

example 2:

class Super {

void function(){}

}

class Child extends Super{

@override
int function(){
 return 10;
}

you can override a function that have a type of void and change the type of the function to anything else.


Solution 2: jamesdlin

The callback you pass to forEach() would be inferred as a bool Function(int), and List<int>.forEach() expects a void Function(int). This is accepted since T Function() is considered a subtype of void Function(); T Function() is substitutable anywhere void Function() is used.