Flutter - How to align selected item from DropdownButton?
just add Center as parent to child of DropdownMenuItem
DropdownButton(
items: genderList
.map((string) => DropdownMenuItem(
child: Center(
child: Text(
string,
style: Theme.of(context).textTheme.bodyText2,
),
),
))
.toList(),
onChanged: (value) { },
)
Incase someone stumble upon this issue. You need to specify width and this can be achieved by using selectedItemBuilder
property of DropdownButton
.
final List<String> items = <String>['1','2','3'];
String selectedItem = '1';
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: DropdownButton<String>(
value: selectedItem,
hint: Container(
alignment: Alignment.centerRight,
width: 180,
child: Text("Hint text", textAlign: TextAlign.end)
),
onChanged: (String string) => setState(() => selectedItem = string),
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return Container(
alignment: Alignment.centerRight,
width: 180,
child: Text(item, textAlign: TextAlign.end)
);
}).toList();
},
items: items.map((String item) {
return DropdownMenuItem<String>(
child: Text('Log $item'),
value: item,
);
}).toList(),
),
);
}
code from here
You probably won't need this now but if anyone is wondering how I found the following solution.
DropdownButton(
hint: Align(alignment: Alignment.centerRight, child: Text('any text')),
...
items: _dropdownValues.map((item) {
return DropdownMenuItem(
child: new Align(alignment: Alignment.centerRight, child: Text(item)),
value: item,);
}).toList(),
)
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(),
// ...
),