如何使用 ListView 将元素放在彼此之下?

How to put elements under each other with a ListView?

当涉及到 ListView 时,我很难将项目放在一起。

我有这个代码:

body:
    Column(
        children: [
            Text('foo'),
            Expanded(
                child: ListView.builder(
                    controller:     ...,
                    itemCount:      ...,
                    itemBuilder:    ... 
                )
            ),
            Text('bar')
        ]
    )
,

它给了我左边的结果,但我想要右边的结果:

我试图将 ListView 放入容器中(带有 height: double.maxFinite),但它给了我一个:Bottom overflowed by X pixels.

Edit :这是我想要达到的结果(运行 "full page") :

body {
  font-size: 18px;
  margin: 0;
  padding: 0;
}

.mobile {
  position: relative;
  width: 320px;
  margin: 0 auto;
  border: 1px solid cyan;
  max-height: 400px;
  overflow-y: scroll;
  padding-top: 41px;
}

.appbar {
  position: fixed;
  top: 0;
  width: 300px;
  background: rgba(0, 0, 0, 1);
  color: white;
  padding: 10px;
}

.text {
  background: rgba(255, 0, 0, .3);
  padding: 10px;
}

.list-view {
  background: rgba(0, 255, 0, .3);
  padding: 10px;
  min-height: 500px;
}
<div class="mobile">
  <div class="appbar">AppBar</div>
  <div class="text">Text</div>
  <div class="list-view">ListView</div>
  <div class="text">Text</div>
</div>

试试这个

body: Column( children: [ Text('foo'), Expanded( child: Container( child: ListView.builder( shrinkWrap: true, itemBuilder: ......., itemCount: ....., ), ), ), Text('bar') ] ) ,

这段代码对我有用。

您可以将顶部和底部的 foo 和 bar 添加为列表的第一项和最后一项。 ListView 将有 list.length + 2 项。

  body: Column(children: [
    Text('foo'),
    Expanded(
      child: ListView.builder(
        itemCount: list.length + 2,
        itemBuilder: (context, index) {
          if (index == 0)
            return Text("foo");
          else if (index < list.length + 1)
            return Text("$index");
          else
            return Text('bar');
        },
      ),
    ),
  ]),

您必须使用 CustomScrollView

CustomScrollView(
    slivers: <Widget>[
      SliverToBoxAdapter(
        child: Text("Text"),
      ),
      SliverList(
        delegate: SliverChildListDelegate( [
              Container(
                height: 200.0,
                decoration: BoxDecoration(color: Colors.orange),
              ),
              Container(
                height: 400.0,
                decoration: BoxDecoration(color: Colors.pink),
              ),
              Container(
                height: 500.0,
                decoration: BoxDecoration(color: Colors.blue),
              )
            ]),
      ),
      SliverToBoxAdapter(
        child: Text("Text"),
      ),
    ],
  ) 

请注意,您可以使用 SliverChildListDelegate 或 SliverChildBuilderDelegate