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.
The contains() method is used to check if an element occurs in a list. This method takes one parameter and returns a boolean value indicating whether or not that item is found in the list.
where method Null safety. Returns a new lazy Iterable with all elements that satisfy the predicate test . The matching elements have the same order in the returned iterable as they have in iterator. This method returns a view of the mapped elements.
There are two types of list: Fixed length list. Growable list.
You can use array. asMap(). containsKey(index) to check if the Key index exists or not in Array List. In this way, you can check if Array List has a Key index or value or not in Dart or Flutter.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With