简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM