gsk
gsk

Reputation: 107

Flutter: How to create a new list with only one class member?

I have a class named Recyclable with many members, including title, description, and recyclable. I then created an object named recyclable using the class Recyclable as follows:

List<Recyclable> recyclable = [
  Recyclable('myTitle', 'myDescription', 'is recyclable'),
  Recyclable('myTitle2', 'myDescription2', 'is recyclable'),
];

Now, I want to copy the object recyclable but only with the title information. In other words, I want to create a list named newInfo as below:

List<String> newInfo = List.from(recyclable.title);

However, there is a red underline below .title, and I have no idea how to fix this.

Upvotes: 1

Views: 249

Answers (1)

Lapa Ny Aina Tanjona
Lapa Ny Aina Tanjona

Reputation: 1268

Try the code below :

List<Recyclable> recyclable = [
    Recyclable('myTitle', 'myDescription', 'is recyclable'),
    Recyclable('myTitle2', 'myDescription2', 'is recyclable'),
  ];

  List<String> newInfo = recyclable.map((item) {
    return item.title;
  }).toList();
  print(newInfo);
  //[myTitle, myTitle2]

The Recyclable class :

class Recyclable {
  String title;
  String description;
  String isRecyclable;

  Recyclable(this.title, this.description, this.isRecyclable);
}

Upvotes: 1

Related Questions