Home > other >  How to modify a item from List of Maps in Flutter | Dart
How to modify a item from List of Maps in Flutter | Dart

Time:11-25

I have a list of Map items. From this i want to modify a key value of an item by using it's id. The below is the List of map.

List items = [{'id':'01','name':'Rahul'},{'id':'02','name':'John'},{'id':'03','name':'Marry'}];

From this list when i press a button i want to update the name of that item based on id.

For eg,

void editName(String id,String name){
  //Here i want to edit the name based on that id
} 

if i pass editName('02','Rose') i want the result

[{'id':'01','name':'Rahul'},{'id':'02','name':'Rose'},{'id':'03','name':'Marry'}];

CodePudding user response:

void main() {
  List<Map<String, String>> items = [
    {'id': '01', 'name': 'Rahul'},
    {'id': '02', 'name': 'John'},
    {'id': '03', 'name': 'Marry'}
  ];

  void editName(String id, String name) {
    for (var item in items) {
      if (id == item['id']) {
        item['name'] = name;
      }
    }
  }

  editName('02', 'Rose');
  print('items: $items');
}

CodePudding user response:

I Found the Solution :)

void main() {
List items = [{'id':'01','name':'Rahul'},{'id':'02','name':'John'},{'id':'03','name':'Marry'}];
var result = items.firstWhere((element) => element['id'] == '02');
print(result);
var index = items.indexWhere((element) => element['id'] == '02');
print(index);
result['name'] = 'Rose';
print(result);
items.removeAt(index);
items.insert(index, result);
print(items);
}

  • Related