3

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}];

5 Answers 5

3
final List<Map<String, dynamic>> mapList = stringList.map(
    (s) => {'name': s, 'selected': false}
).toList();
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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}]

Comments

1
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}] 

Comments

0

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},
];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.