Home > Software design >  Item in list are getting duplicated when list.add() method is called
Item in list are getting duplicated when list.add() method is called

Time:08-12

I have created a empty list of type Map<String, dynamic>,

List<Map<String, dynamic>> list = [];

when i try to add an item in it. It is added to the list but when i try to add another item in it is added in list and all the previous items are replaced with the new item added. all the items are becoming same each time i am adding a new item in it. The code is actually very lengthy and i want to make the question simple so i can not include the code here and i have added the link to the code file please check this out and tell me what i am doing wrong item and list printed screenshot

CodePudding user response:

The problem is you are using the same map to add value to the list. As the map is callByReference it will change the value inside the list when the value of the map is changed.

To fix the issue you can change the addition method to map like

_addItemtoList() {
if (_formKey.currentState!.validate()) {
  _formKey.currentState!.save();
  list.add(Map.from(productInfo));
  total  = productInfo["product_rate"] * productInfo["product_quantity"];
  FocusManager.instance.primaryFocus!.unfocus();
  _formKey.currentState!.reset();
  productController.clear();
  rateController.clear();
}

this you probably solve your issue

  • Related