[英]Centering the selected value of a DropdownButton
我能够将提供给DropDownButton
DropdownMenuItem
使用的文本项居中,但是当菜单关闭时,所选项目如何居中?
Something like this:像这样的东西:
DropdownMenuItem<int>(
value: model.id,
child: SizedBox(
width: width,
child: Text(
model.toString(),
textAlign: TextAlign.center, //this will do that
),
),
)
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(),
),
You can do that by wrapping your DropdownMenuItem
's child Text
in a Container
and provide it width
along with alignment
.您可以通过将
DropdownMenuItem
的子Text
包装在Container
并为其提供width
和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),
);
}
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;
});
},
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.