I am able to center the text items used in DropdownMenuItem
s provided to the DropDownButton
, but how can the selected item be centered when the menu is closed?
Asked
Active
Viewed 3,102 times
0

CopsOnRoad
- 237,138
- 77
- 654
- 440

AlanKley
- 4,592
- 8
- 40
- 53
4 Answers
1
This worked for me:
List<String> targetOptions = ['No target', '1', '2', '3', '4'];
return DropdownButton<String>(
value: target,
selectedItemBuilder: (BuildContext context) {
return targetOptions.map<Widget>((String item) {
return SizedBox(width: 70, child: Center(child: Text(item, style: TextStyle(color: Colors.white))));
}).toList();
},
items: targetOptions.map((String value) {
return new DropdownMenuItem<String>(
value: value == 'No target' ? '0' : value,
child: Center(
child: new Text(
value,
style: TextStyle(color: Colors.white),
),
),
);
}).toList(),
onChanged: (val) {
SettingManager.put(SettingManager.SETTING_DAILY_TARGET, val);
setState(() {
target = val;
});
},
)

user3930989
- 39
- 1
- 4
0
Something like this:
DropdownMenuItem<int>(
value: model.id,
child: SizedBox(
width: width,
child: Text(
model.toString(),
textAlign: TextAlign.center, //this will do that
),
),
)

Harsh Bhikadia
- 10,095
- 9
- 49
- 70
-
Note: Text should have a fixed width container to align center. – Harsh Bhikadia Apr 12 '19 at 04:28
-
OP asked to center the items when it is closed, your answer doesn't do that. – CopsOnRoad Apr 12 '19 at 07:19
0
I am using something like this:
String dropdownValue = 'One';
DropdownButton<String>(
value: dropdownValue,
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>['One', 'Two', 'three', 'Four'].map((item) {
return DropdownMenuItem<String>(
value: item,
child: Builder(builder: (BuildContext context) {
final bool isDropDown = context.ancestorStateOfType(TypeMatcher<_MyAppState>()) == null;
if (!isDropDown) {
return Center(child: Text(item), widthFactor: 2,);
} else {
return Text(item);
}
},)
);
}).toList(),
),

Kalpesh Kundanani
- 5,413
- 4
- 22
- 32
0
You can do that by wrapping your DropdownMenuItem
's child Text
in a Container
and provide it width
along with alignment
.
int _value = 0;
Widget _buildDropdown() {
return DropdownButton(
value: _value,
items: [
DropdownMenuItem(
value: 0,
child: Container(
child: Text("Zero"),
width: 200,
alignment: Alignment.center,
),
),
DropdownMenuItem(
value: 1,
child: Container(
child: Text("One"),
width: 200,
alignment: Alignment.center,
),
),
],
onChanged: (value) => setState(() => _value = value),
);
}

CopsOnRoad
- 237,138
- 77
- 654
- 440
-
This works but a hard coded width is not going to work as a general purpose solution. – AlanKley Apr 13 '19 at 03:22
-
@AlanKley Agreed but as of now there is no way to do it except giving it a hard coded width or full width of the screen. – CopsOnRoad Apr 13 '19 at 06:12