0

I have a List<MyClass> myClass;, I want to get List<String> myList; from all of myClass.item, is there one line way to convert it?

1
  • read List.map official documentation (and Iterable documentation in general) Commented Dec 5, 2020 at 15:14

1 Answer 1

2

You can use the map method from List class to loop through the entire list. Don't forget to call toList in the end, as Dart's map returns a kind of Iterable. Please see the code below.

class Employee {
  int id;
  String firstName;
  String lastName;
  Employee(
    this.id,
    this.firstName,
    this.lastName,
  );
}

void main() {
  List<Employee> employees = <Employee>[
    Employee(1, "Adam", "Black"),
    Employee(2, "Adrian", "Abraham"),
    Employee(3, "Alan", "Allan"),
  ];

  List<String> myList = employees.map((item)=>item.firstName).toList();
  print(myList);
}
Sign up to request clarification or add additional context in comments.

2 Comments

How can I do if I just need ["Adam", "Adrian", "Alan"]?
Updated my answer please see the code above.

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.