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
You could use
map
method.We need to be a bit careful. Your code
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, thenindexWhere
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:
(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: