Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push/insert key value pair list into a list in dart/flutter?

Tags:

flutter

dart

I have a list where I am trying to push in a another list, but it keeps throwing error

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
like image 339
Manas Avatar asked Dec 11 '22 02:12

Manas


1 Answers

You need to initialize your list

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

You should consider typing your lists because if you are not careful enough, your current code can cause errors. Something like this:

List<Product> products = [];
Product myProduct = Product(name: "Product 1", price: 2.0, quantity: 3);
products.add(myProduct);
like image 116
Martyns Avatar answered Jun 07 '23 03:06

Martyns