Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return from a forEach loop in Dart?

Tags:

for-loop

dart

I have this function

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

    return false;
  }

It always return false, even if the condition is satisfied.

Any ideas?

like image 396
Patrioticcow Avatar asked Sep 01 '25 22:09

Patrioticcow


2 Answers

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;
  }
like image 107
Günter Zöchbauer Avatar answered Sep 03 '25 16:09

Günter Zöchbauer


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());
like image 32
Reimer Behrends Avatar answered Sep 03 '25 17:09

Reimer Behrends