Mohammed Ali
Mohammed Ali

Reputation: 1185

Flutter Dart get list of string from list of objects

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

Upvotes: 12

Views: 21561

Answers (5)

omega_mi
omega_mi

Reputation: 718

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]

Upvotes: 1

Aashis Shrestha
Aashis Shrestha

Reputation: 612

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

Upvotes: 4

Shak Shared
Shak Shared

Reputation: 63

It's simple and cumbersome though,

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

Upvotes: 6

Alex Hartford
Alex Hartford

Reputation: 5970

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

Upvotes: 40

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12353

List<String> names=[];

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

Upvotes: 0

Related Questions