如何在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
}

您不能为Response本身添加任何值;这就是你想要做的。你所能做的就是将它存储为一个变量,然后你就可以对数据进行操作了。

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}}

我创建了一个虚拟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;

最新更新