简体   繁体   English

如何修改Flutter中地图列表中的项目| Dart

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

I have a list of Map items.我有 Map 项的列表。 From this i want to modify a key value of an item by using it's id.由此我想通过使用它的 id 来修改项目的键值。 The below is the List of map.以下是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.从这个列表中,当我按下一个按钮时,我想根据 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如果我通过editName('02','Rose')我想要结果

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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