Home > Software engineering >  how to updates the value of Map in List flutter
how to updates the value of Map in List flutter

Time:12-28

// I have this type of list List data = [{1: false}, {2: false}, {5: false}, {6: false}]

// I want to updates only true false values List afterUpdates= [{1: true}, {2: false}, {5: false}, {6: true}]

CodePudding user response:

You can do it by following simple 3 steps

  1. Find the element to update
  2. Find the index of that element in your array and update it
  3. Replace the element in array using the index you found

here is a simple logic for it you can test it at dartpad

void main() {
 List<Map<int, bool>> data = [{1: false}, {2: false}, {5: false}, {6: false}];
  
  updateKey(key,val){
    print("before");
    print(data);
    var element= data.firstWhere((k)=>k.keys.contains(key),orElse:()=>{});
    var index = data.indexOf(element);
     print("index");
    print(index);
    element.update(key,(v)=>val);
    data[index]=element;
    print("after");
    print(data);
  }
  updateKey(1,true);
  updateKey(6,true);
  
  }

CodePudding user response:

 data.update(index, (value) => true);

Change the index via loop

  • Related