skip to Main Content

i have the following List

List myList = [
{'name':'Alex'},
{'name':'Ali'},
{'name':'jack'},
{'name':'Alex'},
{'name':'Alex'},
];

Now i want update all item that the name == ‘Alex’ to ‘Andy’

so i tried the following

int wantedIndex =  myList.indexWhere((element) =>  element['name']=='Alex');
  myList[wantedIndex] = {'name':'Andy'} ;

since the indexWhere is only get the first target index so it will update one item only.

so How could i achieve this with all item that == ‘Alex’ ?

2

Answers


  1. You could use map method.

    myList.map((item) {
      if (item['name'] == 'Alex') item['name'] = 'Andy';
    }).toList();
    
    print(myList); // [{name: Andy}, {name: Ali}, {name: jack}, {name: Andy}, {name: Andy}]
    
    Login or Signup to reply.
  2. We need to be a bit careful. Your code

    int wantedIndex =  myList.indexWhere((element) =>  element['name']=='Alex');
    myList[wantedIndex] = {'name':'Andy'} ;
    

    is actually replacing any map with key "name" set to "Alex" with a new map with key "name" set to "Andy". Let’s say that the original datum was {'name': 'Alex', 'age': 'ten'}, your code would replace it with {'name': 'Andy'}, and the "age" data would be lost. That might or might not matter, depending on the context. Also, your code is assuming that there is such an element in the list; if there isn’t, then indexWhere returns -1, which could be an issue.

    For this type of problem, using a recursive solution is often helpful. For example, using the logic you used in your post:

    void update(List<Map<String, String>> data) {
      final index = data.indexWhere((element) => element["name"] == "Alex");
      if (index != -1) update(data..[index]["name"] = "Andy");
    }
    

    (Notice, if there are other key-value pairs in the data, they are not lost, and if there are no matches, there is no problem with indexing.)

    Then we could just do:

    update(myList);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search