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):
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
- Maintain a list of platform which will be used to filter
- Check with the
games
whether it has the item present in thegamesList
or not- 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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.