Sarmed MQ Berwari
Sarmed MQ Berwari

Reputation: 99

Flutter : How change modify unmodifiable map

I have list like this in provider:

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();
}

in provider when I use this methos to chane indexed order with another:

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

I get this error type '(dynamic) => dynamic' is not a subtype of type '(Object) => Object' of 'update'

and when I use this :

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

I get this error Unsupported operation: Cannot modify unmodifiable map

Add More Details

the item in changeOrder method comes from screen contain orders :

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

Upvotes: 1

Views: 2249

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63829

orders type is List<Map<String, dynamic>>. While reading the item, it will be a map instead of list.

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

And you can use both way you;ve tried.

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

Upvotes: 0

Related Questions