我的DropDownButtonFormField的选定项目与项目列表中的项目不同。
这是我想做的
class CurrencyDropDown extends StatefulWidget {
const CurrencyDropDown({
Key key,
}) : super(key: key);
@override
_CurrencyDropDownState createState() => _CurrencyDropDownState();
}
class _CurrencyDropDownState extends State<CurrencyDropDown> {
String selected = "EUR";
@override
Widget build(BuildContext context) {
return DropdownButtonFormField<String>(
value: selected,
hint: new Text("Select your currency...", textAlign: TextAlign.center),
items: ["USD", "EUR", "CHF"]
.map((label) => DropdownMenuItem(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Image.asset(
'icons/currency/${label.toLowerCase()}.png',
package: 'currency_icons',
width: 30,
),
Text(label),
],
),
value: label,
))
.toList(),
onChanged: (value) {
setState(() => selected = value);
},
);
}
}
并像这样显示小部件
return SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
height: 30,
width: 200,
child: CurrencyDropDown(),
),
我希望所选值具有与下拉列表相同的显示,并具有良好的间距和对齐方式。
您选择的项目与下拉菜单不同的原因是,您选择的字段中的行宽度被压缩。您可以通过添加DropdownButtonFormField
isExpanded: true,
使用selectedItemBuilder
使用任何小部件进行自己选择的设计。请用selectedItemBuilder
检查以下更改并检查输出。
class _CurrencyDropDownState extends State<CurrencyDropDown> {
String selected = "EUR";
@override
Widget build(BuildContext context) {
return DropdownButtonFormField<String>(
value: selected,
hint: new Text("Select your currency...",
textAlign: TextAlign.center),
items: ["USD", "EUR", "CHF"]
.map((label) => DropdownMenuItem(
child: Row(
children: <Widget>[
Icon(Icons.assessment, size: 30),
SizedBox(
width: 100,
),
Text(label),
],
),
value: label,
)).toList(),
onChanged: (value) {
setState(() => selected = value);
},
selectedItemBuilder: (BuildContext context) {
return ["USD", "EUR", "CHF"].map<Widget>((String item) {
return Row(
children: <Widget>[
Icon(Icons.assessment, size: 30),
SizedBox(
width: 100,
),
Text(item),
],
);
}).toList();
},
);
}
}
输出