How to set right alignment for a selected item of DropdownButtonFormField with Flutter?

Issue

I have a DropdownButtonFormField with Flutter like this:

                  DropdownButtonFormField<String>(
                    decoration: InputDecoration(
                      labelText: "My Label",
                      labelStyle: const TextStyle(fontSize: 20),
                      isDense: true,
                      contentPadding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
                    ),

                    items: ["No", "Yes"].map((label) => DropdownMenuItem(
                      alignment: Alignment.centerRight,
                      child: Text(label),
                      value: label,
                      )).toList(),

                    onChanged: (value) {
                      ....
                    },
                    value: "No",
                    alignment: Alignment.centerRight,
                  ),

which generates:

enter image description here

However the No/Yes values are displayed with a left alignment. Is it possible to display them on the right?

Solution

We can trick the UI using selectedItemBuilder and LayoutBuilder on top of DropdownButtonFormField.

 LayoutBuilder(
  builder: (context, constraints) => DropdownButtonFormField<String>(
   //....
    selectedItemBuilder: (c) => ["No", "Yes"]
        .map(
          (e) => SizedBox(
            width: constraints.maxWidth - 24, //-default dropDownIconSize
            child: Text(
              e,
              textAlign: TextAlign.right,
            ),
          ),
        )
        .toList(),
   //....

enter image description here

Answered By – Yeasin Sheikh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published