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 1: Benjamin Corben

I would do something like this:

List<Game> games = getAllGames();
List<Game> filteredGames = [];
List<String> platformsToFilterBy = ['MAC', 'PC'];
games.where((game) => game.platforms.where((platform) {
   if (platformsToFilterBy.contains(platform.name)) {
      filteredGames.add(game);
   }
}));


Solution 2: orotype

void main() {
List<Game> games = [
Game(1, "mario", ["Linux", "Mac", "Windows"]),
Game(2, "Zelda", ["Mac", "Windows", "Playstation"]),
Game(3, "Wow", ["Windows"]),
];

var filters = ["Linux", "Playstation"];

for (String filter in filters) { games.removeWhere((game) => game.platforms.contains(filter)); }

for (var game in games) { print(game.name); // Wow } }

class Game { final int id; final String name; final List platforms;

Game(this.id, this.name, this.platforms); }


Solution 3: Alok

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
}