I would like to obtain an object from a List based on a specific search criteria of its member variable
this is the code I am using
class foo
{
foo(this._a);
int _a;
}
List<foo> lst = new List<foo>();
main()
{
foo f = new foo(12);
lst.add(f);
List<foo> result = lst.where( (foo m) {
return m._a == 12;
});
print(result[0]._a);
}
I am getting the error and not sure how to resolve this
Uncaught exception:
TypeError: Instance of 'WhereIterable<foo>': type 'WhereIterable<foo>' is not a subtype of type 'List<foo>'
I am trying to search for an object whose member variable a == 12
. Any suggestions on what I might be doing wrong ?
The method indexOf() returns the index of the first occurrence of the element in the list if found. Otherwise, it returns -1.
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];
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>
.
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