我有一个列表,我试图在其中推送另一个列表,但它不断抛出错误
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
Run Code Online (Sandbox Code Playgroud)
您需要初始化您的列表
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);
Run Code Online (Sandbox Code Playgroud)
您应该考虑输入您的列表,因为如果您不够小心,您当前的代码可能会导致错误。像这样的东西:
List<Product> products = [];
Product myProduct = Product(name: "Product 1", price: 2.0, quantity: 3);
products.add(myProduct);
Run Code Online (Sandbox Code Playgroud)