【发布时间】:2020-05-25 20:31:45
【问题描述】:
当我将新项目添加到我的列表时,它将覆盖之前的值。我想追加列表,但没有发生
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,),),
),
],
),
),
我有一个ListView,ListView 项目将从 API 获取,当我单击一个项目时,我希望它添加到列表中,我可以将其保存在 sharedpreference 中。但是每次我点击之前的按钮时,都会被新的按钮覆盖。
以下是将数据转换为 JSON 格式的代码
List<String> addedItems(List<dynamic> cartList){
try {
var res = cartList.map((v) => json.encode(v)).toList();
return res;
} catch (err) {
// Just in case
return [];
}
},
输出是
-
当我添加第一项时
[{"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}] -
当我再次添加相同的项目时
[{"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}](数量增加)
-
当我添加一个新项目时
[{"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}](DINE SPECIALs 在哪里?)
但我想要像这样的输出
[{"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}]
【问题讨论】: