[英]How to make a horizontal ListView in flutter take as much height as its children max height, placed in a column?
我在一列中放置了一個水平的ListView
,我希望它的高度只需要它的高度。 一種方法是將ListView
包裝在SizedBox
中並為其指定一個特定的硬編碼height
。 此外,將其包裝在Expanded
小部件中將導致ListView
占用列中的額外可用空間。 但是,我希望它自動達到它只需要的高度。 如何實現? 謝謝你。
示例代碼如下:
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
children: [
Text("Hi there!"),
SizedBox(
height: 50,
child: ListView(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
children: List.generate(
4,
(index) => Text("Item $index "),
),
),
),
ElevatedButton(
onPressed: () {},
child: Text("This is a button"),
),
],
),
),
),
);
}
不幸的是,這是不可能的。 ListView
可能有很多項目(甚至是無限的),因此找出“最大的一個”需要遍歷每個項目,這與使用ListView
的重點背道而馳。
如果您只有幾個項目,則可以改用Row
小部件。 如果您需要滾動,請使用SingleChildScrollView
包裹Row
。
例如:
Column(
children: [
Container(
color: Colors.green.shade100,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
FlutterLogo(),
FlutterLogo(size: 100),
for (int i = 0; i < 50; i++) FlutterLogo(),
],
),
),
),
const Text('The row has ended.'),
],
)
演示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.