How can I convert my List to List<Map<String,dynamic>>? The selected
field value will always be false.
List<String> stringList = ["one", "two", "three"];
List<Map<String, dynamic>> mapList = [
{"name": "one","selected": false},
{"name": "two","selected": false},
{"name": "three", "selected": false}];
CodePudding user response:
Do you need something like this?
List<String> stringList = ["one", "two", "three"];
List<Map<String, dynamic>> mapList = [];
stringList.forEach((element) {
mapList.add({"name": "$element", "selected": false});
});
It will loop the stringList array and take each element and put it in the mapList
CodePudding user response:
Try out this
void main() {
List<String> stringList = ["one", "two", "three"];
List<Map<String, dynamic>> mapList = [];
stringList.forEach((e) {
Map<String, dynamic> item = {"name": e, "selected": false};
mapList.add(item);
});
print(mapList);
}
output:
[
{name: one, selected: false},
{name: two, selected: false},
{name: three, selected: false}]
CodePudding user response:
void main() {
List<String> stringList = ["one", "two", "three"];
List<Map<String, dynamic>> mapList = [];
for (var element in stringList) {
mapList.add({"name": element, "selected": false});}
print(mapList);
}
output
[{name: one, selected: false},
{name: two, selected: false},
{name: three, selected: false}]
CodePudding user response:
final List<Map<String, dynamic>> mapList = stringList.map(
(s) => {'name': s, 'selected': false}
).toList();
CodePudding user response:
There are several ways to accomplish this, but I believe the most idiomatic solution would be to use collection for. Effective dart recommends DO use collection literals when possible.
List<Map<String, dynamic>> mapList = [
for (final element in stringList)
{"name": element, "selected": false},
];