[英]Flutter: How to create a DropdownMenuItem with a ListTile as child
我想创建一个 DropDownButton,其中 DropDownMenuItem 有一个 ListTile() 作为子项,而不是通常的 Text() 小部件。 还有一个类似的问题问在这里,但很不幸,答案doesnn't似乎工作。
这是我的代码:
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 的宽度将延伸到无穷大)。
到目前为止我尝试过的解决方案:
我试图将 ListTile 的“宽度”设置为特定值,但 ListTile 没有属性“宽度”。
我已经将 ListTile-Widget 包装在一个 Expanded-Widget 中。 但这也不起作用。
有解决办法吗?
提前致谢!
ListTile 没有任何限制,将尝试使用尽可能多的空间。 如果您使用具有固定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.