Bollie
Bollie

Reputation: 517

Flutter Complex Sorting of a List

I have two Lists

List 1 contains an object. One of the aspects of that object is a person ID [1,2,3,4,5] and List 2 contains the person ID's whom match a criteria [1,3,5]

I need to filter list 1 to only show the objects where the criteria is met.

Something like:

 var sortedList = list1
          .where((item) => item.personID == "Any of the ids contained within list2)
          .toList();

Therefore sortedList = the objects for id 1,3,5

Upvotes: 0

Views: 538

Answers (1)

ejabu
ejabu

Reputation: 3147

Short answer

Iterable<Item> filteredList = list.where((element) {
    return list2
        .map((elem) => elem.personId)
        .toList()
        .contains(element.personId);
  });

You may look into this Dart Playground. Dartpad

Full Script

class Item {
  int personId;
  Item({this.personId});

  String toString() {
    return "$personId";
  }
}

List<Item> list = [
  Item(personId: 1),
  Item(personId: 2),
  Item(personId: 3),
  Item(personId: 4),
  Item(personId: 5),
];

List<Item> list2 = [
  Item(personId: 1),
  Item(personId: 3),
  Item(personId: 5),
];

void runFunction() {
  Iterable<Item> filteredList = list.where((element) {
    return list2
        .map((elem) => elem.personId)
        .toList()
        .contains(element.personId);
  });
  List<Item> result = filteredList.toList();
  print(result);
}

main() {
  runFunction();
}

Upvotes: 1

Related Questions