Flutter:如何修改不可修改的地图



我在提供者中有这样的列表:

List orders=[]:
void getOrders(){
orders = [
{"id":1,
"order":[
{"id":1,"name":"mike"},
{"id":2,"name":"john"},
{"id":3,"name":"smith"}
]
},
{"id":1,
"order":[
{"id":1,"name":"roz"},
{"id":2,"name":"sam"},
{"id":3,"name":"ruby"}
]
},
];
notifyListeners();
}

在提供者中,当我使用这种方法与另一种方法更改索引顺序时:

void changeOrder(orderIndex,item){
orders[orderIndex].update("order",(val)=>item);
notifyListeners();
}

我收到这个错误type '(dynamic) => dynamic' is not a subtype of type '(Object) => Object' of 'update'

当我使用这个:

void changeOrder(orderIndex,item){
orders[orderIndex]["order"]=item;
notifyListeners();
}

我收到这个错误Unsupported operation: Cannot modify unmodifiable map

添加更多详细信息

changeOrder方法中的项目来自包含订单的屏幕:

var item = List.from(orders[index]);

orders类型为List<Map<String, dynamic>>。当阅读item时,它将是一个地图而不是列表。

Map item = Map.from(orders[index]);

你可以双向使用;我试过了。

List<Map<String, dynamic>> orders = [];
void getOrders() {
orders = [
{
"id": 1,
"order": [
{"id": 1, "name": "mike"},
{"id": 2, "name": "john"},
{"id": 3, "name": "smith"}
]
},
{
"id": 1,
"order": [
{"id": 1, "name": "roz"},
{"id": 2, "name": "sam"},
{"id": 3, "name": "ruby"}
]
},
];
}
void changeOrder(orderIndex, item) {
orders[orderIndex]["order"] = item;
// orders[orderIndex].update("order", (val) => item);
}
void main(List<String> args) {
getOrders();
print(orders);
Map item = Map.from(orders[1]);
changeOrder(1, item);
print(orders);
}

最新更新