ImAZ
ImAZ

Reputation: 59

How to add data using loop in list in Flutter

I have a 2-d list, I am adding data using `

quotationList.add( [productName.text, double.parse(productPrice.text), _n] );`

output is:

[[qwe, 555.0, 1], [qwe 1, 5555.0, 2]]

now i want to add this 2-d list into my products list, i can't figure out how to do that? my products list looks like this, with static data

final products = <Product>[
    Product('1', "random text", 3.99, 2),
    Product('2', "random text", 15, 2),
    Product('3', "random text", 6.95, 3),
    Product('4', "random text", 49.99, 4),
  ];

i want to make make it dynamic using some loops or something, like this

final products = <Product>[
    for(int i=0; i<quotationList.length; i++)
    {
      Product(i.toString(), quotationList[i][0], quotationList[i][1], quotationList[i][2]),
    }
];

but i got this error

The element type 'Set<Product>' can't be assigned to the list type 'Product'.

Upvotes: 0

Views: 13254

Answers (3)

Hemanth Raj
Hemanth Raj

Reputation: 34769

The issue is the {} braces for the for loop inside the list.

Change it to:

final products = <Product>[
      for (int i = 0; i < quotationList.length; i++)
        Product(
          i.toString(),
          quotationList[i][0],
          quotationList[i][1],
          quotationList[i][2],
        ),
    ];

The loops inside lists and maps don't have {}, because there aren't multiline.

Upvotes: 3

camillo777
camillo777

Reputation: 2367

this is a full working code:

void main() {
  List quotationList = List();
  quotationList.add(["name1", 10.0, 100]);
  quotationList.add(["name2", 10.0, 100]);
  quotationList.add(["name3", 10.0, 100]);
  quotationList.add(["name4", 10.0, 100]);

  List products = quotationList
      .asMap()
      .map((index, quotation) => MapEntry(
          index,
          Product(
            index,
            quotation[0].toString(),
            quotation[1],
            quotation[2],
          )))
      .values
      .toList();

  for (Product p in products) print(p.name);
}

class Product {
  final int index;
  final String name;
  final double price;
  final int n;

  Product(this.index, this.name, this.price, this.n);
}

Hope it helps!

The conversion from List to Map is needed (asMap) because you need an index as well. If you do not need an index you can use the map method directly on the list.

Upvotes: 2

M.B
M.B

Reputation: 619

try this

final products = [
    for(int i=0; i<quotationList.length; i++)
    {
      Product(i.toString(), quotationList[i][0], quotationList[i][1], quotationList[i][2]),
    }
];

Upvotes: 1

Related Questions