I got following problem which I can’t solved 🙁
Scenario: I have a list with Ingredients and I want to compare it with a recipes list which holds a list of ingredients depending on the recipes.
List<RecipeList> recipesList = [
RecipeList(recipeName: "Cake", itemNames: ["banana", "appel"]),
RecipeList(recipeName: "Soup", itemNames: ["potatato", "egg"]),
RecipeList(recipeName: "Sandwich", itemNames: ["Toast", "Sausage", "Ketchup"]),
RecipeList(recipeName: "Pizza", itemNames: ["Tomato", "Mushroom"]),
];
List inventory = ["coke", "egg", "banana", "apple"];
class RecipeList {
String? recipeName;
List<String>? itemNames;
RecipeList({this.recipeName, this.itemNames});
}
I am thankful for any help or idea :D!
Thank you very much for your help,
ReeN
>Solution :
I would start by changing the inventory to be a Set<String>. This will allow you to more efficiently check for subsets using the containsAll method.
You can then call where on the recipesList to get all of the elements where the inventory contains all of the itemNames for the given RecipeList object.
See implementation below:
List<RecipeList> recipesList = [
// fixed misspelling of "apple"
RecipeList(recipeName: "Cake", itemNames: ["banana", "apple"]),
RecipeList(recipeName: "Soup", itemNames: ["potatato", "egg"]),
RecipeList(
recipeName: "Sandwich", itemNames: ["Toast", "Sausage", "Ketchup"]),
RecipeList(recipeName: "Pizza", itemNames: ["Tomato", "Mushroom"]),
];
// change inventory to a Set<String>
Set<String> inventory = {"coke", "egg", "banana", "apple"};
class RecipeList {
String? recipeName;
List<String>? itemNames;
RecipeList({this.recipeName, this.itemNames});
}
void main() {
var results =
recipesList.where((v) => inventory.containsAll(v.itemNames ?? []));
for (var result in results) {
print(result.recipeName);
}
}