how to merge more than one list into only one list? dart

538

Solution 1

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;
}

Solution 2

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));
Share:
538
ialyzaafan
Author by

ialyzaafan

Iam a mobile application developer and a frontend developer Love to learn new technologies Experience : Flutter , reactJs , IOS

Updated on December 19, 2022

Comments

  • ialyzaafan
    ialyzaafan over 1 year

    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

    • pskink
      pskink about 4 years
      what is your input data? how can you assign a product to shop? i am assuming that Product.id is "product ID" and not "ID of shop that product belongs to"
  • ialyzaafan
    ialyzaafan about 4 years
    okay but i have a dynamic number of shops not constant is there a way to loop on List<Shop> shops and create the all products List ?
  • ialyzaafan
    ialyzaafan about 4 years
    okay but i have a dynamic number of shops not constant is there a way to loop on List<Shop> shops and create the all products List ?
  • asterisk12
    asterisk12 about 4 years
    If my answer helped, please mark it correct so that other people who might have the same problem can see it!
  • ialyzaafan
    ialyzaafan about 4 years
    The expression here has a type of 'void', and therefore can't be used. Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void
  • konstantin_doncov
    konstantin_doncov about 4 years
    @ialyzaafan did this help you?
  • asterisk12
    asterisk12 about 4 years
    To help you further, I would have to see your code!