flutterdartdrop-down-menuiconsflutter-dropdownbutton

How to add suffix icon only to the DropdownMenuItem in the DropdownButtonFormField?


I am trying to add Icons.close to each item in the DropdownMenuItem. When the icon is pressed the item will be removed from the list.

But the problem is, The icon is also showing in the Dropdown button value. I only want the string to be shown in the dropdown button value.

Something like this.

DropDownButton :

DropDownButton

DropDownMenuItem :

DropDownMenuItem

This is my code:

SizedBox(
    width: kWidth * 0.1,
    child: DropdownButtonFormField(
      focusColor: Colors.transparent,
      decoration: InputDecoration(
        filled: true,
        fillColor: Colors.transparent,
        focusColor: Colors.transparent,
        hoverColor: Colors.transparent,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: kBlack),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: kBlack),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: kBlack),
        ),
        disabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: kBlack),
        ),
        focusedErrorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: kBlack),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: const BorderSide(color: kBlack),
        ),
      ),
      value: homePageViewModel.selectedDistrict.value,
      items: homePageViewModel.districtList.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(value),
              const Icon(
                Icons.close,
                color: kBlack,
              ),
            ],
          ),
        );
      }).toList(),
      onChanged: (value) {
     homePageViewModel.selectedDistrict.value = value!;  
     },
    ),
  );

Solution

  • You can do like the below code, but if you want to show the icon in the first item you should select different item value

     Text(value),
                        homePageViewModel.selectedDistrict.value != value
                            ? const Icon(
                                Icons.close,
                              )
                            : const SizedBox(),