[英]Centering the selected value of a DropdownButton
我能夠將提供給DropDownButton
DropdownMenuItem
使用的文本項居中,但是當菜單關閉時,所選項目如何居中?
像這樣的東西:
DropdownMenuItem<int>(
value: model.id,
child: SizedBox(
width: width,
child: Text(
model.toString(),
textAlign: TextAlign.center, //this will do that
),
),
)
我正在使用這樣的東西:
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(),
),
您可以通過將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),
);
}
這對我有用:
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.