How to return from a forEach loop in Dart?

↘锁芯ラ 提交于 2020-04-12 18:02:10

问题


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?


回答1:


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;
  }



回答2:


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());



回答3:


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.



来源:https://stackoverflow.com/questions/50336082/how-to-return-from-a-foreach-loop-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!