Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

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 ?

like image 735
Rajeshwar Avatar asked Jun 16 '18 23:06

Rajeshwar


People also ask

How do you find the index of an element in a list Dart?

The method indexOf() returns the index of the first occurrence of the element in the list if found. Otherwise, it returns -1.


2 Answers

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];
like image 80
lrn Avatar answered Oct 25 '22 11:10

lrn


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>.

like image 23
Tobe Osakwe Avatar answered Oct 25 '22 12:10

Tobe Osakwe