[英]Flutter: How to create a DropdownMenuItem with a ListTile as child
I want to create a DropDownButton where the DropDownMenuItem has a ListTile() as child, instead of an usual Text() widget.我想创建一个 DropDownButton,其中 DropDownMenuItem 有一个 ListTile() 作为子项,而不是通常的 Text() 小部件。 There is a similar question asked here , but unfortunately the answer doesnn't seem to work.
还有一个类似的问题问在这里,但很不幸,答案doesnn't似乎工作。
Here is my code:这是我的代码:
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 Exception is thrown:抛出以下异常:
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
I have done some research about this exception, but all I have found were articles/tutorials dealing with columns and rows.我对这个异常做了一些研究,但我发现的只是处理列和行的文章/教程。 What exactly is the problem?
究竟是什么问题? (As far as I understand it, the ListTile will stretch in width to infinity).
(据我所知,ListTile 的宽度将延伸到无穷大)。
Solutions I have tried so far:到目前为止我尝试过的解决方案:
I tried to set the "width" of the ListTile to a specific value, but the ListTile doesn't have a property "width".我试图将 ListTile 的“宽度”设置为特定值,但 ListTile 没有属性“宽度”。
I have wrapped the ListTile-Widget in an Expanded-Widget.我已经将 ListTile-Widget 包装在一个 Expanded-Widget 中。 But this didn't work too.
但这也不起作用。
Is there a solution?有解决办法吗?
Thanks in advance!提前致谢!
The ListTile has no constraints and will try to use as much space as possible. ListTile 没有任何限制,将尝试使用尽可能多的空间。 If you wrap your
ListTile
with a Container
with fixed height
and width
, you will no longer have a problem:如果您使用具有固定
height
和width
的Container
包裹您的ListTile
,您将不再有问题:
Widget getListTile(String value) {
return Container(
height: 60,
width: 100,
child: ListTile(
leading: Text('FooBar'),
title: Text(value),
trailing: Icon(Icons.euro_symbol),
),
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.