Mapping key value pairs in the dropdown button

const countries = {
‘nepal’: ‘+977’,
‘india’: ‘+909’
}

How to map it into the dropdown button? When i select nepal, value +977 should appear and when i select india, value +909 should appear…

1 Like

I have implemented something similar in MyApp. Modified a bit to make it similar to your use case. This will definitely help you.

First Create a List of DropDownMenuItems.

class Country {
  final String code;
  final String name;

  Country({this.code, this.name});
}

const countries = {
‘nepal’: ‘+977’,
‘india’: ‘+909’
}
List<Country> countryList = [];
countries.forEach((name, code) {
countryList.add(Country(name: name, code: code)); //parse each object and add to the list of Countries
});

setCountryItems(countryList); // call the function to create DropDownMenuItemList
  setCountryItems(List<Country> countryList) {
List<DropdownMenuItem<String>> countryListDropDown = [];
    for (Country country in countryList) {
      setState(() {
        countryListDropDown.add(new DropdownMenuItem(
            value: country.name,
            child: Text(
              country.name,
              style: TextStyle(fontSize: 20),
            )));
      });
    }
  }
  Widget countryDropDown(String label, List<DropdownMenuItem<String>> countryListDropDown) {
    Country currentCountry;
    return Container(
      margin: EdgeInsets.all(25),
      child: DropdownButton(
        elevation: 20,
        isExpanded: true,
        items: list,
        value: currentCountry == null ? null : currentCountry.name,
        icon: Icon(
          Icons.arrow_drop_down,
        ),
        hint: Text(
          label,
          style: TextStyle(color: Colors.black, fontSize: 25),
        ),
        onChanged: (item) {
          setState(() {
            currentCountry = countryList.firstWhere(
                (loc) => loc.name == item,
                orElse: () => countryList.first);
          });
        },
      ),
    );
  }

Now currentCountry holds the currently selected Country object. You can access the code by currentCountry.code;

2 Likes

thank u so much @sakina

1 Like