The return type 'bool' isn't a 'void', as required by the closure's context dart flutter

Viewed 15320

I am getting the below error when using the forEach loop for the items when used in the function when returning the values.

bool validatedValues(List<String> values){
    values.forEach((i){
      if (i.length > 3){
        return true;
      }
    });
    return false;
  }

Im using dart null safety sdk version: ">=2.12.0 <3.0.0"

Complete error:

The return type 'bool' isn't a 'void', as required by the closure's context.dartreturn_of_invalid_type_from_closure
1 Answers

The problem is caused by the return true inside your forEach. forEach is expecting a void Function(T) not a bool Function(T).

I think that what you try to achieve is:

bool validatedValues(List<String> values){
  bool result = false;
  values.forEach((i){
    if (i.length > 3){
      result = true;
    }
  });
  return result;
}

Or, probably more elegant:

bool validatedValues(List<String> values) => values.any((i) => i.length > 3);
  • bool any(bool test(E element));

    This returns true if at least one item of the List is validated by test. ref

  • bool every(bool test(E element));

    This return true if all the items of the List are validated by func. ref

Related