What Dart's List's "some" method is called? Method checking if at least one element passes a test

3,054

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);
Share:
3,054
Vince Varga
Author by

Vince Varga

Updated on December 17, 2022

Comments

  • Vince Varga
    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 called where, and so on. However, I can't seem to find some's equivalent.