Asbah Riyas
Asbah Riyas

Reputation: 986

Flutter Firestore, How to add list of objects in array

I need to add list of objects in firestore as shown in the images. i could only add two list with the below code

 onPressed: () {
        _fireStore.collection('notifyseller').document().updateData({
          'Customer': userName,
          "address": controller.text,
          "mobile": mobileNumber,
          "Item": FieldValue.arrayUnion([
            {
              "name": itemName.toList()[0],
              "price": rate.toList()[0],
              "quantity": quantity.toList()[0]
            },
           {
              "name": itemName.toList()[1],
              "price": rate.toList()[1],
              "quantity": quantity.toList()[1]
            },
          ]),
        });
      },

here itemName.toList() contains list of strings. by the above code i can only add two data. i need to add all the item in the itemName.toList() to that array, instead of giving index for each array


enter image description here

Upvotes: 5

Views: 12844

Answers (2)

Aakash
Aakash

Reputation: 41

i did this way

class Item{
String name;
String price;
String qty;

//named constructor here

Map<String, dynamic> toMap() {
    return {
      'name': name,
      'price': price,
      'qty':qty,
    };
  }
}
List<Items> items = [Item(name:"",price:"",qty:""),Item(name:"",price:"",qty:"")]
    
_fireStore.collection('notifyseller').document().updateData({
  'Customer': userName,
  "address": controller.text,
  "mobile": mobileNumber,
  "Item":, items.map<Map>((e)=> e.toMap()).toList();
});

Upvotes: 2

Ali Bayram
Ali Bayram

Reputation: 7941

If you are sure that your three list have same length try this;

List yourItemList = [];
for (int i = 0; i < itemName.length; i++)
  yourItemList.add({
    "name": itemName.toList()[i],
    "price": rate.toList()[i],
    "quantity": quantity.toList()[i]
  });

_fireStore.collection('notifyseller').document().updateData({
  'Customer': userName,
  "address": controller.text,
  "mobile": mobileNumber,
  "Item": FieldValue.arrayUnion(yourItemList),
});

Upvotes: 6

Related Questions