I have list of names want to add them to map and add each record of this map to list Like this
List<String> items = [
'Item1',
'Item2',
'Item3',
'Item4',
'Item5',
'Item6',
'Item7',
'Item8',
];
List all=[];
Map <String, dynamic>test={};
me(){
for(int i=0; i<items.length;i ){
test["one"]=items[i];
test["check"]=false;
all.add(test);
}
test["check"]=false); });
print(all);
The output was
[{one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}]
The item8 was always repeated but I want this output
[{one: Item1, check: false}, {one: Item2, check: false}, {one: Item3, check: false}, {one: Item4, check: false}, {one: Item5, check: false}, {one: Item6, check: false}, {one: Item7, check: false}, {one: Item8, check: false}]
CodePudding user response:
You can use:
final results = items.map((e) => {"one": e, "check": false}).toList();
void main() {
List<String> items = [
'Item1',
'Item2',
'Item3',
'Item4',
'Item5',
'Item6',
'Item7',
'Item8',
];
final results = items.map((e) => {"one": e, "check": false}).toList();
print(results);
}
Prints:
[{one: Item1, check: false}, {one: Item2, check: false}, {one: Item3, check: false}, {one: Item4, check: false}, {one: Item5, check: false}, {one: Item6, check: false}, {one: Item7, check: false}, {one: Item8, check: false}]
Or: using your approach with a for
loop:
final results = [];
for (var i = 0; i < items.length; i ) {
results.add({"one": items[i], "check": false});
}
CodePudding user response:
You can do this:
final all = items
.map(
(item) => {
'one': item,
'check': false,
},
)
.toList();