【问题标题】:How to get the same attribute from all objects in a list in one line如何从一行列表中的所有对象中获取相同的属性
【发布时间】:2020-07-06 05:29:37
【问题描述】:

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

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

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

重要的是我直接返回这些属性的列表,而不是正常的 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);  
}

【问题讨论】:

    标签: list object flutter dart attributes


    【解决方案1】:

    您可以使用地图功能来实现这一点

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

    【讨论】:

      【解决方案2】:

      只需查看以下代码:

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

      Blow 是输出:

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

      【讨论】:

        猜你喜欢
        • 2021-08-11
        • 1970-01-01
        • 2017-01-07
        • 1970-01-01
        • 2021-11-30
        • 2019-06-26
        • 2018-04-13
        • 2012-11-11
        • 1970-01-01
        相关资源
        最近更新 更多