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