krishnaacharyaa
krishnaacharyaa

Reputation: 24980

How to stop re-orderring of the array elements when updating array elements in firebase

I am actually trying to change the quantity of the cart item , and every time i change , the whole product gets re-ordered by itself,

I am not able to figure out based on what the elements are being re-ordered.

How to stop this from happening?

Before Updating the quantity the cart items are as follows

enter image description here

After updating the quantity the cart items are as follows, The product gets reordered automatically.

enter image description here

My code for updating is :

 void setQuantity(CartItemModel item, int quantity) {
    removeCartItem(item);
    item.quantity = quantity;
    item.cost = (int.parse(item.price!) * item.quantity!).toString();
    utilityController.updateUserData({
      'cart': FieldValue.arrayUnion([item.toJson()])
    });
  }

It's because the array element is deleted and then added , But how to overcome this problem !!

Upvotes: 1

Views: 130

Answers (1)

LeadDreamer
LeadDreamer

Reputation: 3499

Firestore "arrays" are ABSOLUTELY NOT ARRAYS - they are "ordered lists" - the "number" is their order, not an index. The ORDER of the entries in the object are important, as well, so:

{
id: "xxxxxx",
img: "xxxxx",
name: "xxxxx",
nameKa: "xxxxx"
}

WILL NOT MATCH

{
id: "xxxxxx",
name: "xxxxxx",
nameKa: "xxxxxx",
img: "xxxxxx",
}

Firestore's scale and speed come from indexing entries, and an "array" (ordered list) of objects is essentially indexed by a string-like representation of the object.

Firestore "arrays" (ordered lists) of objects are remarkably difficult to use, and give you no advantages - they are much better suited to "single value" entries. I would strongly recommend using a sub-collection of documents (each member in it's own document), where you can trivially query (either a a collection or collectionGroup) to find individual documents.

Upvotes: 1

Related Questions