如何在一行中从列表中的所有对象获取相同的属性

How to get the same attribute from all objects in a list in one line

我有一个相同 class 的对象列表。 此 class 包含我要使用的属性。

我想在一行中列出所有这些属性。这可能吗?

这是一个小例子:我只想要一个所有颜色的列表。

重要的是,我 return 直接列出这些属性,而不是正常的 forEach 语句。

void main() {

List<Car> listOfCars = [
   Car('blue'), 
   Car('green'),
   Car('yellow'),
 ];
}

//List<String> listOfColors = listOfCars[all].color;

class Car{
  String color;
  Car(this.color);  
}

可以使用map函数来实现

 List<String> listOfColors = listOfCars.map((car) => car.color).toList();
  print(listOfColors);

只需查看下面的代码:

void main() {

   List<Car> listOfCars = [
    Car('blue'),
    Car('green'),
    Car('yellow'),
  ];
  List<String> stringList = List();

  // This is where you get the single car object and then you add it the list of string
  for (int i = 0; i < listOfCars.length; i++) {
      stringList.add(listOfCars[i].color);
    }

// this is the desired out put  i have just printed your list :
    print('This is the string length : ' + stringList.length.toString());
    for (int i = 0; i < stringList.length; i++) {
      print('This is the string list :' + stringList[i]);
    }
 }

class Car {
  final String color;

  Car(this.color);
}


打击是输出:

This is the string length : 3
This is the string list :blue
This is the string list :green
This is the string list :yellow