问题
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