skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

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

  2. 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');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search