【问题标题】:How to make DropdownButton menu width to fit text?如何使 DropdownButton 菜单宽度适合文本?
【发布时间】:2021-11-02 21:55:45
【问题描述】:

我想要一个下拉按钮,其宽度基于菜单文本长度。下拉箭头在文本之间没有任何额外的间距。 像这样:

目前,我得到了这个:

我的下拉按钮箭头是根据最长的文本定位的。

我的代码:

Widget dropdownList(){
    return Container(
      child: DropdownButton<Location>(
          value: _selectedValue,
          icon: const Icon(Icons.expand_more),
          iconSize: 30,
          underline: SizedBox(),
          onChanged: (Location? newValue) {
            setState(() {
              _selectedValue = newValue!;
            });
          },
          style: const TextStyle(color: Colors.blue),
          selectedItemBuilder: (BuildContext context) {
            return locationList.map((Location value) {
              return Container(
                child: Text(
                  value.name,
                  style: const TextStyle(color: Colors.black,fontSize: 30,
                                    fontWeight: FontWeight.w300),
                ),
              );
            }).toList();
          },
          items: locationList.map<DropdownMenuItem<Location>>((Location value) {
            return DropdownMenuItem<Location>(
              value: value,
              child: Text(value.name, style: TextStyle(color: Colors.black,fontSize: 15,
                                  fontWeight: FontWeight.w300)),
            );
          }).toList(),
        ),
    );
  }

【问题讨论】:

  • 我不是 Flutter 开发者,但在 css display:inline-block 中,文本可以解决问题

标签: flutter flutter-layout dropdown


【解决方案1】:

根据documentations,DropDownButton 有一个名为 isExpanded 的属性:

isExpanded → bool
Set the dropdown's inner contents to horizontally fill its parent. [...]
final

所以就设置好了:

isExpanded = true;

【讨论】:

  • 您好,我不想关注其父级,但我希望下拉菜单为其显示文本的长度
  • 我认为您应该为每个项目创建一个单独的下拉按钮。或更改源代码。
  • 我将您的建议视为一个想法,并使用不同的小部件来实现它。不要认为通过 DropDownButton 是可行的。谢谢!
  • @Huiting 你介意分享你使用哪个小部件来实现这一点吗?我面临着类似的困境,无法弄清楚。
  • @Igor 嗨,我不得不放弃使用DropdownButton。相反,a 创建了一个具有这些布局的容器,然后 onPressed 打开了一个包含项目列表的新页面。
猜你喜欢
  • 2015-02-27
  • 1970-01-01
  • 2015-07-05
  • 2023-03-08
  • 1970-01-01
  • 2013-10-20
  • 2014-05-07
  • 2012-10-19
  • 2016-04-06
相关资源
最近更新 更多