How do I create a dropdownList from Provider ? (Flutter)

Issue

I have created a city model, and have created a provider class for that,

class CityModel {
  String cityId;
  String cityName;

  CityModel({this.cityId, this.cityName});
}

This is the provider class

class CitiesProviders extends ChangeNotifier {
  List<CityModel> citiesData = [];

  void addData(CityModel data) {
    citiesData.add(data);
    notifyListeners();
  }

  List<String> get cityNames {
    List<String> names = [];
    citiesData.map((value) {
      names.add(value.cityName);
    });
    return names;
  }
}

I’m just looking to get the names of cities from the citiesData list and use that name list to create a dropdown.

DropdownButton<String>(
      value: currVal,
      items: Provider.of<CitiesProviders>(context)
          .cityNames
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      onChanged: (value) {
        currVal = value;
      },
    ),

But I’m not getting anything on the screen, also there is no error message. Am I doing everything correct ? Or is there a better way to do this ? Any suggestions and answers would help. Thank you!

Solution

My mistake!

List<String> get cityNames {
    List<String> names = [];
    citiesData.map((value) {
      names.add(value.cityName);
    }).toList(); // Added here
    return name)s;
  }

I added toList() and it’s working now.

Answered By – Sanchit Rastogi

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.