Dart – Filter list in list which contain at least one element

Issue

I’m trying to filter a list of games by a list of platforms.

For example, I got this list of games (Game1, Game2, Game3, Game4):

enter image description here

I want to be able to filter this list to get all PC and MAC games (it must return [Game1, Game2, Game3])

Currently I can filter my list only with one platform ID, but not with a list of platform:

var filteredGames  games.where((g) > g.platforms.any((p) > p.id  /*PC or MAC*/)).toList();

Thank you for your help.

Solution

Using your code only, it required just little modifications and you are good to go. Just use contains() from the list which you will have for checking the list of games platforms

Algo

  1. Maintain a list of platform which will be used to filter
  2. Check with the games whether it has the item present in the gamesList or not
  3. Store in the variable for filtered data

Answer Code

games.where((game) > game.platforms.any((p) > gamesList.contains(p))).toList();

Example

// this is for maintaining multiple list for check
List<String> gamesList  ['PC', 'MAC'];

var filteredList  games.where((game) > game.platforms.any((p) > gamesList.contains(p))).toList();

print(filteredList); // [Instance of 'Game', Instance of 'Game', Instance of 'Game']

for(var game in filteredList){
  print(game.name);  // Game1, Game2, Game4
}

Answered By – Alok

Leave a Comment