Flutter Dart get list of string from list of objects

Viewed 7175

I have a list of objects (City) that contains a lot of properties it's internal structure:

class City {
  String id;
  String name;
  String parent_id;
  double lat;
  double lng;
  String local;
}

how to get a list of names(Strings) from the same list of cities

List<City> cities

how to get List<String> names from cities

3 Answers

Use map. Tutorial here.

For example:

class City {
  const City(this.id, this.name);

  final int id;
  final String name;
}

List<City> cities = [
  City(0, 'A'),
  City(1, 'B'),
  City(2, 'C'),
];

final List<String> cityNames = cities.map((city) => city.name).toList();

void main() {
  print(cityNames);
}

It's simple and cumbersome though,

var cityNames = cities.map((c) => c.name).toList().join(',');
List<String> names=[];

for (City city in cities){
names.add(city.name);
 }
Related