How to push object value instead of reference of the object in array

Viewed 160

I created an object and tried to push it on one array. When I tried to add an object the first time in the array so it's added perfectly, but when I edit the object and again push the object to the same array. But both values in the array look like same.

In an array it's pushing reference of my object, when it's changed, then also reflected in the array.

Can please someone help me to push object values in the array not the reference of the object?

void checkedItem(int id) {
    obj!.clear();
    obj = {
      "id": id,
      "items": {
        "artical": "",
        "item": "",
        "vol": "",
        "pc/ctm": "",
        "total": "",
        "option": false,
        "action": "",
      },
    };

    filterList!['special_cases'].forEach((data) {
      if (data['value'] == true) {
        temp.add(obj);
      }
    });
    filterList!['categories'].forEach((data) {
      data['subCategories'].forEach((item) {
        if (item['value'] == true) {
          obj!['items']['item'] = item['name'];
          temp.add(obj);
        }
      });
    });
    // print(temp);
    update();
  }

  void addPhaseItem() {
    phaseData.add(temp);
    print(phaseData);
    Get.back();
    temp.clear();
    update();
  } 

output of my code

1 Answers

Replace

temp.add(obj);

with

temp.add({...obj}); // note the curly braces for maps and sets

in all cases.

"..." is the spread operator, and allows you to insert items from one collection into another. You can read more about them on the Dart Language Tour page.

Related