12

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

5 Answers 5

40

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);
}
Sign up to request clarification or add additional context in comments.

Comments

6

It's simple and cumbersome though,

var cityNames = cities.map((c) => c.name).toList().join(',');

Comments

4

Use this

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

You can also go through explanation below

CustomData Class

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

Map List<City> to List<String> based on any member of City class

List<City> cities= getListOfCities();
// city.name, city.local...any field as you wish
List<String> cityNameList = cities.map((city) => city.name).toList();
print(cityNameList);

Comments

2

An alternative, if you want to extract a list of string from list of object, with selected or enabled flag.

To do that, you can remove objects with selected=false or something like name.length > 5, then do map.tolist to extract the list of string.

Usually i use this method to get filters to filtering search result. Example we have a products list with distance & country filters. We can simply use solution above and apply filter with selected true.

I don't speak english, hope you understand 😅.

class City {
  const City(this.name, [this.selected= false]);

  final String name;
  final bool selected;
}

void main() {
  final cities = [City('A'), City('B', true), City('C')];
  cities.add(City('D', true));
  
  /// Remove unselected items
  cities.removeWhere((e) => !e.selected);
   
  /// extract list of string from list of objects
  final selectedCities = cities.map((c) => c.name).toList();

  print(selectedCities);
}

print:

[B, D]

Comments

0
List<String> names=[];

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.