I have the following List
[
{thumb: 28986/H6a6Xkm_thumb.jpeg, full: 28986/H6a6Xkm.jpeg},
{thumb: 28986/f-2_thumb.jpg, full: 28986/f-2.jpg},
{thumb: 28986/Ft_thumb.jpg, full: 28986/Ft.jpg},
{thumb: 28986/FED_thumb.jpg, full: FED.jpg}
]
I wanted to try to add a new property to each of these 4 items called desc
which would be a description, lets say for now: Apple
Is there an easy way to iterate the list and insert the new property so the final result would be:
[
{thumb: 28986/H6a6Xkm_thumb.jpeg, full: 28986/H6a6Xkm.jpeg, desc: Apple},
{thumb: 28986/f-2_thumb.jpg, full: 28986/f-2.jpg, desc: Apple},
{thumb: 28986/Ft_thumb.jpg, full: 28986/Ft.jpg, desc: Apple},
{thumb: 28986/FED_thumb.jpg, full: FED.jpg, desc: Apple}
]
CodePudding user response:
Yes, you can iterate over the list with map
method and inside it return the new map with the spread operator like this:
final myList = [{"hello": "world"}];
final newList = myList.map((obj) => {...obj, "desc": "Apple"}).toList();
CodePudding user response:
Is your list a list of maps?
The easiest way to edit every value in a list is using the .map
method:
myList = myList.map((value) => newValue).toList();
so for example say you have a list of numbers and want to add one to each of them
myList = myList.map((number) => number 1).toList();
you can also pass more calculations like so:
myList = myList.map((value) {
// some calculations
return newValue;
}).toList();
Here is how to solve your problem with that code assuming your list is List<Map<String, dynamic>>
myList = myList.map((value) => value..addAll({'desc': 'apple'})).toList();
CodePudding user response:
You can use an for loop or the forEach list property to add an element to the lists:
void main() async {
var list = [
{'thumb': '28986/H6a6Xkm_thumb.jpeg', 'full': '28986/H6a6Xkm.jpeg'},
{'thumb': '28986/f-2_thumb.jpg', 'full': '28986/f-2.jpg'},
{'thumb': '28986/Ft_thumb.jpg', 'full': '28986/Ft.jpg'},
{'thumb': '28986/FED_thumb.jpg', 'full': 'FED.jpg'}
];
/// using for loop
for (int i = 0; i < list.length; i ) list[i]['desc_for'] = 'Apple';
print(list);
/// Using forEach
list.forEach((item) {
item['desc_forEach'] = 'Apple';
});
print(list);
}