When I add new item to my list, it will overwrites earlier value. I want to append the list, but it is not happening

Container(
  // color: Colors.red,
  child: Row(
    mainAxisAlignment: MainAxisAlignment.end,
    children: <Widget>[
      Container(
        width: 50,
        height: 50,
        // color: Colors.blue,
        child: FlatButton(onPressed: (){
          if(_itemCount > 0){
            setState(() {
              _itemCount--;
            });

          }
        }, child: Image(image: AssetImage("images/minus.png"),width: 20,height: 20,),),
      ),
      Container(
        child: Text("$_itemCount"),
      ),
      Container(
        width: 50,
        height: 50,
        //  color: Colors.green,
        child: FlatButton(onPressed: () async{
          setState(() {
            _itemCount++;
          });

          cartItemList = [{"index":widget.intex,"itemObj":widget.items,"quantity":_itemCount}];
          print(addedItems(cartItemList));

          final prefs = await SharedPreferences.getInstance();
          await prefs.setStringList('itemList', addedItems(cartItemList));
        }, child: Image(image: AssetImage("images/plus.png"),width: 20,height: 20,),),
      ),
    ],
  ),
),

I have a ListView, ListView items will fetch from API, when I click one item I want it add to a list, which I can save in sharedpreference. but every time I click on a button earlier one overwritten by new one.

below is the code to convert the data to JSON format

List<String> addedItems(List<dynamic> cartList){
  try {
    var res = cartList.map((v) => json.encode(v)).toList();
    return res;
  } catch (err) {
    // Just in case
    return [];
  }
},

Output is

  1. When I add first item

     [{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":1}]
    
  2. When I add same item again

     [{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":2}]
    

    (quantity increased)

  3. When I add a new item

     [{"itemObj":{"item_price":20.0,"item_name":"English Breakfast","item_img":" ","item_code":"002","item_discount":0.0,"item_id":71,"category_id":12},"quantity":1}]
    

    (Where are the DINE SPECIALs?)


But I want output like

[{"itemObj":{"item_price":22.0,"item_name":"DINE SPECIAL BREAKFAST","item_img":" ","item_code":"001","item_discount":0.0,"item_id":552,"category_id":12},"quantity":2},{"item_price":20.0,"item_name":"English Breakfast","item_img":" ","item_code":"002","item_discount":0.0,"item_id":71,"category_id":12},"quantity":1}]


Solution 1: Ulaş Kasım

you set list every time you click button like this

cartItemList = [{"index":widget.intex,"itemObj":widget.items,"quantity":_itemCount}];

maybe you need to do is

cartItemList.add({"index":widget.intex,"itemObj":widget.items,"quantity":_itemCount});