What Dart's List's "some" method is called? Method checking if at least one element passes a test
Huh! The problem was that the equivalent of JavaScript's some
method is a method on the Iterable
class and not on the List
. The List
class implements the Iterable
, though, so I could have found it earlier, but I guess I was lost in all those method descriptions.
Dart's equivalent of the some
method is called: any
:
Iterable<E>
bool any(bool test(E element))
Checks whether any element of this iterable satisfies
test
.Checks every element in iteration order, and returns true if any of them make test return true, otherwise returns false.
Example usage:
// The list in which we want to check if there is an item that passes a certain test.
List<String> haystack = [
// It contains some elements...
];
// Just to be explicit in this example, you don't really need it
typedef TestFunc = bool Function(String);
// The test. Just some function that takes an element and returns boolean.
TestFunc isNeedle = (String v) => v.toLowerCase().contains('needle');
bool gotNeedle = haystack.any(isNeedle);
Vince Varga
Updated on December 17, 2022Comments
-
Vince Varga over 1 year
On JavaScript arrays, there is the
some
method:The
some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.I think there must be a similar method on the Dart lists, too, but I just can't seem to find it anywhere on the internet or in the
List
docs.I got used to Dart having different names for some of the methods, so I always spend like 5 minutes until I remember that JavaScript's
find
is calledwhere
, and so on. However, I can't seem to findsome
's equivalent.