The DropdownButton
in Flutter sets its width based on the largest DropdownMenuItem
from the items it has. That leaves a lot of white space between the item and the arrow if a small item is selected. How do I make the button scale to just fit the selected item's width?
I tried using Expanded
, some Flexible
stuff and I still can't make it change its width.
DropdownButton(
value: null,
hint: Text("Small text"),
items: ..., //Text widgets that have more text and are larger than the hint
)
I am trying to get rid of that space underlined between the hint
and the arrow:
You can make the menu open above the button by setting showAboveButton to true. You can edit (button, menu and menu items) height, width and decoration as you want. You can align hint or value and customize them.
To change the dropdown Button color in Flutter, simply wrap your DropdownButton widget inside the Container and provide the styling instructions inside the decoration property using the BoxDecoration widget. Using the color property (insideBoxDecoration) you can assign the color.
If we want to display some other text instead of the selected option on the button we will use selectedItemBuilder. DropdownButton( value: _value, selectedItemBuilder: (BuildContext context) { return list_items. map<Widget>((int item) { return Text('item $item'); }). toList(); }, items: list_items.
Option 1: Set DropDown. dart selectedItemOffset to -40 in then DropDownItems will always opens below the DropdownButton .
The width is actually determined by the widest item provided by the selectedItemBuilder argument (which uses the items if not defined). With this little trick I managed to have it working:
DropdownButton<T>(
value: value,
selectedItemBuilder: (ctx) => [for (final item in items) value],
items: items,
onChanged: (value) => ... update value
The selectedItemBuilder in the example produces a list of repeated items (the one corresponding to the selected value). You will need a stateful widget to handle the value.
Wrap Dropdown button with ButtonTheme
and add alignedDropdown = true
like:
ButtonTheme(
alignedDropdown: true,
child: DropdownButton(...),
)
alignedDropdown will match the menu items' width with buttons. Then we need specific width, so wrap ButtonTheme with SizedBox or Container:
SizedBox(
width: 25, // Your width for dropdowns
child: ButtonTheme(...),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With