Reputation: 398
i have a
class shop {
int id;
String name;
List<Product> products;
}
class Product {
int id;
String productName;
}
where each shop has his own products , how to merge all shops products in one list how to create a List of all products
Upvotes: 2
Views: 2441
Reputation: 14152
I think you're looking for the fold
function. You can do it in 1 line.
List<Shop> shops = [shop1, shop2, shop3];
List<Product> allProducts = shops.fold<List<Product>>([], (productList, shop) => productList..addAll(shop.products));
Upvotes: 1
Reputation: 2879
You can simply merge Lists
with +
operator:
List<Product> list1 = ...;
List<Product> list2 = ...;
List<Product> list3 = ...;
List<Product> mergedList = list1 + list2 + list3;
Also, Dart 2.3
and higher supports spread operator, which can be used as follows:
List<Product> mergedList2 = [...list1, ...list2, ...list3];
For dynamic number of shops you can use basic forEach:
List<Shop> shops = ...;
List<Product> mergedList = List();
shops.forEach((shop) => mergedList.addAll(shop.products));
Upvotes: 1
Reputation: 412
You can merge lists using + or the spread operator
Using the Addition Operator:
List<shop> shops = [shop1, shop2];
List<Product> products = shop1.products + shop2.products;
Using Spread Operator:
List<Product> products = [...shop1.products, ...shop2.products];
Edit
You would need to do it like this:
List<shop> shops = [shop1, shop2,...];
List<Product> mergedProducts = []
for(int i = 0; i < shops.length; i++){
mergedProducts = mergedProducts + shops[i].products;
}
Upvotes: 1