首页 > 解决方案 > 如何将类列表的成员转换为列表在一行代码中?

问题描述

我有一个List<MyClass> myClass;,我想List<String> myList;从所有 myClass.item 中获取,有没有一种方法可以转换它?

标签: listflutter

解决方案


您可以使用 List 类中的 map 方法遍历整个列表。最后不要忘记调用 toList,因为 Dart 的 map 返回一种 Iterable。请看下面的代码。

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

推荐阅读