Searching a List of objects for a particular object in dart using "where"

The Iterable.where method returns an iterable of all the members which satisfy your test, not just one, and it's a lazily computed iterable, not a list. You can use lst.where(test).toList() to create a list, but that's overkill if you only need the first element.

You can use lst.firstWhere(test) instead to only return the first element, or you can use lst.where(test).first to do effectively the same thing. In either case, the code will throw if there is no element matched by the test.

To avoid throwing, you can use var result = lst.firstWhere(test, orElse: () => null) so you get null if there is no such element.

Another alternative is

foo result;
int index = lst.indexWhere(test); 
if (index >= 0) result = lst[index];

or you can go crazy and do this:

bool checkIfProductNotFound(Map<String, Object> trendingProduct) {
bool isNotFound = this
    ._MyProductList
    .where((element) => element["id"] == trendingProduct["id"])
    .toList()
    .isEmpty;

return isNotFound ;
}

The answer is simple. Iterable.where returns an Iterable, not a List. AFAIK this is because _WhereIterable does its computations lazily.

If you really need to return a List, call lst.where(...).toList().

Otherwise, you can set result to be an Iterable<foo>, instead of a List<foo>.

Tags:

Dart