如何在 Flutter 列表中使用循环添加数据

How to add data using loop in list in Flutter

我有一个二维列表,我正在使用 `

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

输出为:

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

现在我想将这个二维列表添加到我的产品列表中,我不知道该怎么做? 我的产品列表看起来像这样,带有静态数据

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),
  ];

我想使用一些循环之类的东西让它变得动态,就像这样

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

但我遇到了这个错误

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

问题是列表中 for 循环的 {} 大括号。

改为:

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

列表和映射中的循环没有{},因为没有多行。

试试这个

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

这是完整的工作代码:

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

希望对您有所帮助!

需要从 List 到 Map 的转换 (asMap),因为您还需要一个索引。如果不需要索引可以直接在list上使用map方法