【问题标题】:Flutter: How to create a DropdownMenuItem with a ListTile as childFlutter:如何使用 ListTile 作为子项创建 DropdownMenuItem
【发布时间】:2020-06-23 12:04:53
【问题描述】:

我想创建一个 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 没有“宽度”属性。

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

有解决办法吗?

提前致谢!

【问题讨论】:

    标签: flutter exception dart


    【解决方案1】:

    ListTile 没有任何限制,并且会尝试使用尽可能多的空间。如果你用固定的heightwidth 包裹你的ListTile,你将不再有问题:

    Widget getListTile(String value) {
      return Container(
        height: 60,
        width: 100,
        child: ListTile(
          leading: Text('FooBar'),
          title: Text(value),
          trailing: Icon(Icons.euro_symbol),
        ),
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-13
      • 2021-07-03
      • 2020-10-03
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      相关资源
      最近更新 更多