Search code examples
drop-down-menuflutteralignment

Flutter - How to align selected item from DropdownButton?


I am unable to align the selected item from DropdownButton to the center.

I have tried child: Center() under the DropdownMenuItem, it is able to align those items however after I have selected one of the items, the selected item was aligned to the Left immediately. I would also like to align the selected item to the Center.

Anyone knows how to achieve it?

Thanks in advance.

Unable to align selected item to Center

_dropdownValues:

final List<String> _dropdownValues = [
  "One",
  "Two12345",
  "Three123456789",
  "Four",
  ];

  String _selectedValue;

Under Widget Build:

body: Center(

        child: Row(

          mainAxisAlignment: MainAxisAlignment.center,

          children: <Widget>[
            Container( 
              child: Text('Name:',),
            ),

            Container(

              child: Center(
                child: DropdownButton(
                  hint: Text('Select ...'),
                  items: _dropdownValues.map((value) => DropdownMenuItem(
                    child: Center( child: Text(value), ),
                    value: value,
                  )).toList(),

                  onChanged: (String value) {
                    setState(() {
                      this._selectedValue = value;
                    });
                  },
                  isExpanded: false,
                  value: _selectedValue,
                ),
              ),
            ),
          ],
        ),
      ),

Solution

  • If you don't mind setting a fixed width you can wrap your DropdownMenuItem Text child in a SizedBox. Then you set the textAlign property to TextAlign.center, like so:

    DropdownButton(
      // ...
      items: _dropdownValues.map((value) => DropdownMenuItem(
        child: SizedBox(
          width: 100.0, // for example
          child: Text(value, textAlign: TextAlign.center),
        ),
        value: value,
      )).toList(),
      // ...
    ),