Home > Blockchain >  Update value of a single entry in a List<Map<String, dynamic>> in dart
Update value of a single entry in a List<Map<String, dynamic>> in dart

Time:07-24

I have a list of type Map<String,dynamic>, I fill this list with List.filled.

[{gstatus: 1, vermerk: }, {gstatus: 1, vermerk: }, {gstatus: 1, vermerk: }, {gstatus: 1, vermerk: }]

But if I want to change e.g. the value "vermerk" of the second entry of the list with ".update()", all values of the key "vermerk" change like:

[{gstatus: 1, vermerk: test}, {gstatus: 1, vermerk: test}, {gstatus: 1, vermerk: test}, {gstatus: 1, vermerk: test}]  

I would like to have the following result

[{gstatus: 1, vermerk: }, {gstatus: 1, vermerk: test}, {gstatus: 1, vermerk: }, {gstatus: 1, vermerk: }]  

Here the Code

void main() {
  
  late List<Map<String, dynamic>> deviceForm;
  
  deviceForm = List.filled(4,
          {"gstatus": 1, "vermerk": ""});
  
  print(deviceForm);
  
  deviceForm[1].update('vermerk', (value) => 'test');
  
  print(deviceForm);
  
}

CodePudding user response:

This is very interesting issue, seems like List.filled will produce identical data, because of this somehow every data will be changed if you try to change one of them... and once i check like this, it return TRUE

print(deviceForm[1] == deviceForm[2]); //TRUE

but i try another shot with List.generate, the result will be different

print(deviceForm[1] == deviceForm[2]); //FALSE

If you have specific reason why you use List.filled, maybe this answer will be useless, or in case you have no problem to switch using List.generate, it will solve your problem

deviceForm = List.generate(4, (index) => {"gstatus": 1, "vermerk": ""});

CodePudding user response:

You can try to use generate and update


void main() {
  
  List<Map<String, dynamic>> deviceForm = List.generate(4,
         (index)=> {"gstatus": 1, "vermerk": ""});
  
  print(deviceForm);
  
  deviceForm[1].update('vermerk', (value) => 'test');
  
  print(deviceForm);
  //Output : [{gstatus: 1, vermerk: }, {gstatus: 1, vermerk: test}, {gstatus: 1, vermerk: }, {gstatus: 1, vermerk: }]
}
  • Related