Flutter:如何创建以ListTile作为子项的DropdownMenuItem

问题描述 投票:0回答:1

我想创建一个DropDownButton,其中DropDownMenuItem具有一个ListTile()作为子项,而不是通常的Text()小部件。还有一个类似的问题问here,但不幸的是,该答案似乎无效。

这是我的代码:

class _MyHomePageState extends State<MyHomePage> {
  String choice = 'Item 1';

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Card(
        child: DropdownButton(
          value: choice,
          items: stringItems.map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: getListTile(value),
              // child: Text(value),
            );
          }).toList(),
          onChanged: (String newValue) {
            setState(() {
              choice = newValue;
            });
          }
        )
      ),
    );
  }

  Widget getListTile(String value) {
    return ListTile(
      leading: Text('FooBar'),
      title: Text(value),
      trailing: Icon(Icons.euro_symbol),
    );
  }

  List<String> stringItems = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];
}

引发以下异常:

The following assertion was thrown during performLayout():
BoxConstraints forces an infinite width.
The offending constraints were:
BoxConstraints (w=Infinity, 0.0<=h<=48.0)
The relevant error-causing widget was:
ListTile

我已经对此异常进行了一些研究,但是我发现的只是涉及列和行的文章/教程。到底是什么问题? (据我了解,ListTile的宽度将延伸到无穷大)。

到目前为止我尝试过的解决方案:

  1. 我试图将ListTile的“宽度”设置为特定值,但是ListTile没有属性“ width”。

  2. 我已经将ListTile-Widget包装在Expanded-Widget中。但是这个也没用。

有解决方案吗?

提前感谢!

flutter exception dart
1个回答
0
投票

ListTile没有任何限制,将尝试使用尽可能多的空间。如果用固定了ListTileheight的容器包装width,您将不再有问题:

Widget getListTile(String value) {
  return Container(
    height: 60,
    width: 100,
    child: ListTile(
      leading: Text('FooBar'),
      title: Text(value),
      trailing: Icon(Icons.euro_symbol),
    ),
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.