Search code examples
flutterdropdown

Flutter DropDown Widget issue


I have a dropdown which I want to display countries but I want the value to the country code.

class CountryDropdown extends StatefulWidget {
  const CountryDropdown({Key? key}) : super(key: key);

  @override
  _CountryDropdownState createState() => _CountryDropdownState();
}

class _CountryDropdownState extends State<CountryDropdown> {
  String _selectedCountry = "Austria";

  List<DropdownMenuItem<String>> get dropdownItems {
    List<DropdownMenuItem<String>> menuItems = [
      const DropdownMenuItem(child: Text("Austria"), value: "au"),
      const DropdownMenuItem(child: Text("Belgium"), value: "be"),
      const DropdownMenuItem(child: Text("Croatia"), value: "hr"),
    ];
    return menuItems;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10.0),
      child: DropdownButton<String>(
        value: _selectedCountry,
        hint: const Text('Select a country'),
        onChanged: (newValue) {
          setState(() {
            _selectedCountry = newValue!;
          });
        },
        items: dropdownItems,
      ),
    );

However, if I change the list to this... it works.

const DropdownMenuItem(child: Text("Austria"), value: "Austria"),

Also, if I change to this it works....

const DropdownMenuItem(child: Text("au"), value: "Austria"),

What's going on here?

Here's the error: enter image description here


Solution

  • it is because none of your dropdown item has the value "Austria" like your initial value String _selectedCountry = "Austria"; //chage to "au"

    late String _selectedCountry;
    
    @override
    void initState() {
      _selectedCountry = "au";
      super.initState();
    }