簡體   English   中英

如何使 flutter 中的水平 ListView 的高度與其子項的最大高度一樣高,並放置在一列中?

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

output 是: 在此處輸入圖像描述

但是我想要的( ListView周圍沒有更多或更少的空間): 在此處輸入圖像描述

不幸的是,這是不可能的。 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.'),
  ],
)

演示:

演示 gif

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM