简体   繁体   English

我该怎么做才能将元素插入 Dart 中的现有 object

[英]how can i do to insert an element to an existing object in Dart

"sale": {
   "id": 3,
   "name": "COCA"
}
 
  
 return (response.data['deliveries'] as List).map((delivery) {
      List<void> el = delivery['sale'];

      el.addAll(['price', 500]);
      
    }).toList();
 

"sale": {
    "id": 3,
    "name": "COCA",
    "price": 500
}

You cannot add any value to the Response itself;您不能为Response本身添加任何值; which you are trying to do.你正在尝试做的。 What you can do is store it an variable, and now you can manipulate the data.您可以做的是将它存储为一个变量,现在您可以操作数据了。

  final dummy = <String, dynamic>{
    "sale": {"id": 3, "name": "COCA"},
  };
  print(dummy); // {sale: {id: 3, name: COCA}}

  dummy['sale']['price'] = 500;
  print(dummy); // {sale: {id: 3, name: COCA, price: 500}}

I created a dummy Map<String,dynamic> to replicate your fetched data, you should store it in a variable, then manipulate the data, then return it.我创建了一个虚拟Map<String,dynamic>来复制您获取的数据,您应该将它存储在一个变量中,然后操作数据,然后返回它。

 // storing the data in a variable
 final responseData = response.data['deliveries'];

 // add the new data
 responseData['sales']['price'] = 500;

 // return the variable
 return responseData;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM