在Flutter中,我可以使用DropdownMenuItems构建Dropdown,如下所示:
我添加的DropdownMenuItems总是比下拉列表本身宽:
如何调整DropdownMenuItem的宽度,或删除额外的水平填充?
My DropdownMenuItem小部件如下所示:
DropdownMenuItem(
value: unit.name,
child: Text('hey'),
);
虽然我的Dropdown小部件看起来像这样:
return Container(
width: 300.0,
child: DropdownButtonHideUnderline(
child: DropdownButton(
value: name,
items: listOfDropdownMenuItems,
onChanged: onChanged,
style: Theme.of(context).textTheme.title,
),
),
);
答案 0 :(得分:11)
此功能已添加。见https://github.com/flutter/flutter/pull/14849
现在可以将其包装在ButtonTheme中,并将alignedDropdown
设置为true。
return Container(
width: 300.0,
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton(
value: name,
items: listOfDropdownMenuItems,
onChanged: onChanged,
style: Theme.of(context).textTheme.title,
),
),
),
);
答案 1 :(得分:4)
isExpanded: true
将宽度拉伸到全屏。但是如果你想要一个自定义的下拉菜单。这是我的 customdropdown.dart
import 'package:flutter/material.dart';
class CustomDropDown extends StatelessWidget {
final value;
final List<String> itemsList;
final Color dropdownColor;
final Function(dynamic value) onChanged;
const CustomDropDown({
@required this.value,
@required this.itemsList,
this.dropdownColor,
@required this.onChanged,
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(left: 20, top: 3, bottom: 3, right: 20),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
),
child: DropdownButtonHideUnderline(
child: Padding(
padding: const EdgeInsets.only(left: 14.0, right: 14),
child: DropdownButton(
isExpanded: true,
dropdownColor: dropdownColor,
value: value,
items: itemsList
.map((String item) => DropdownMenuItem<String>(
value: item,
child: Text(item),
))
.toList(),
onChanged: (value) => onChanged(value),
),
),
),
),
);
}
}
现在你可以这样称呼它了。
CustomDropDown(
value: selectedValue,
itemsList: ['Music', 'Photographer'],
onChanged: (value) {
setState(() {
selectedValue = value;
});
},
),
答案 2 :(得分:1)
我通过将isExpanded
更改为true来解决了这个问题;
return Container(
width: 300.0,
child: DropdownButtonHideUnderline(
child: DropdownButton(
isExpanded: true,
value: name,
items: listOfDropdownMenuItems,
onChanged: onChanged,
style: Theme.of(context).textTheme.title,
),
),
);