goutham_mi3
goutham_mi3

Reputation: 345

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

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

Upvotes: 10

Views: 31072

Answers (2)

Ayoub Arroub
Ayoub Arroub

Reputation: 495

You can change foreach by classic for to resolve this

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

you can change it by

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

Upvotes: 0

Thierry
Thierry

Reputation: 8383

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

Upvotes: 16

Related Questions