我有一个列表,我试图在其中添加另一个列表,但它总是抛出错误
List Products;
for(final i productsFromApi){
var tmpArray = [];
tmpArray['name'] = i['name'];
tmpArray['price'] = i['price'];
tmpArray['quantity'] = i['quantity'];
Products.add(tmpArray);
}
print('final list of products');
print(products); // throws an error: add called on null
答案 0 :(得分:2)
您需要初始化列表
List products = [];
for(final i in productsFromApi){
var productMap = {
'name': i['name'],
'price': i['price'],
'quantity': i['quantity'],
}
products.add(productMap);
}
print('final list of products');
print(products);
您应该考虑键入列表,因为如果不够小心,当前代码可能会导致错误。 像这样:
List<Product> products = [];
Product myProduct = Product(name: "Product 1", price: 2.0, quantity: 3);
products.add(myProduct);