How to Create a Single Selected Dropdown List in Flutter?

Advertisements

I am a flutter beginner. How to Create a Single Selected Dropdown List in Flutter?
Like This.
I tried, but I didn’t get what I wanted.

String dropdownvalue = ‘Bahrain’;

            Container(
              width: 308,
              child: DropdownButton(
                // Initial Value
                value: dropdownvalue,

                // Down Arrow Icon
                icon: const Icon(Icons.keyboard_arrow_down),

                // Array list of items
                items: dropdownvalue.map((String dropdownvalue) {
                  return DropdownMenuItem(
                    value: dropdownvalue,
                    child: Text(dropdownvalue),
                  );
                }).toList(),
                // After selecting the desired option,it will
                // change button value to selected value
                onChanged: (String? newValue) {
                  setState(() {
                    dropdownvalue = newValue!;
                  });
                },
              ),
            ),

>Solution :

You should have list of items and selectedItem to manage the list and selection state.

class _YourState extends State<MyHomePage> {
  List<String> countries = [
    'Bahrain',
    'India',
    'Iraq',
    'America',
  ];

  String? dropdownvalue ;

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: Center(
        child: DropdownButton(
          // Initial Value
          value: dropdownvalue,
          icon: const Icon(Icons.keyboard_arrow_down),
          isExpanded: true,
          items: countries.map((String dropdownvalue) {
            return DropdownMenuItem(
              value: dropdownvalue,
              child: Text(dropdownvalue),
            );
          }).toList(),
          hint: Text('Country'),
          onChanged: (String? newValue) {
            setState(() {
              dropdownvalue = newValue!;
            });
          },
        ),
      ),
    );
  }
}

Leave a Reply Cancel reply