首页 > 解决方案 > 如何为 DropDownButtonFormField 设置“选定”项的样式?

问题描述

我的 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(),
            ),

这是选择时的外观 在此处输入图像描述

并显示选择。 在此处输入图像描述

我希望所选值具有与下拉列表中相同的显示,并具有良好的间距和对齐方式。

标签: flutterflutter-layout

解决方案


您选择的项目与您的下拉列表不同的原因是因为您的行宽被压缩在您选择的字段中。您可以通过添加您的DropdownButtonFormField

isExpanded: true,

推荐阅读