How to return from a forEach loop in Dart?

I found this other SO:

How to stop Dart's .forEach()?

In it one of the responses says this:

Dart does not support non-local returns, so returning from a callback won't break the loop. The reason it works in jQuery is that each() checks the value returned by the callback. Dart forEach callback returns void.

I have not located official documentation for this to provide a link. But it makes sense based on similar questions, their answers, and the behavior of your code.

Also based on the other answers in that link you need to do this: Note it uses a "for in" loop rather than foreach. for in functions as a foreach in C# or similar languages function.

bool nameExists(players, player) {
  bool result = false;
  for(var f in players) {
    if (f.data['name'].toLowerCase() == player.toLowerCase()) {
      result = true;
      break;
    }
  }

  return result;
}

Or there are examples of other mechanisms that can be used to achieve the same goal in the linked SO.


There is no way to return a value from forEach. Just use a for loop instead.

  bool nameExists(players, player) {
    for(var f in players) {
      if (f.data['name'].toLowerCase() == player.toLowerCase()) {
        return true;
      }
    }

    return false;
  }

For this specific use case, you can also use any() instead of forEach(), e.g.

bool nameExists(players, player) =>
  players.any((f) => f.data["name"].toLowerCase() == player.toLowerCase());

Tags:

For Loop

Dart