如何使颤振中的水平 ListView 的高度与其 children 最大高度一样高,放置在一列中?

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 在列中获取额外的可用 space。但是,我希望它自动达到它只需要的高度。 如何实现?谢谢。

示例代码如下:

@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"),
              ),
            ],
          ),
        ),
      ),
    );
  }

输出为:

不过我想要的(不多也少space左右ListView):

很遗憾,这是不可能的。 ListView 可能有很多项目(甚至是无限的),因此找出“最大的一个”需要遍历每个项目,这与使用 ListView.[= 的全部要点背道而驰。 17=]

如果您只有几件商品,可以改用 Row 小部件。如果需要滚动,请将 Row 换成 SingleChildScrollView.

例如:

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.'),
  ],
)

演示: