如何在 SingleChildScrollView 中放置列表视图,但是防止它们单独滚动?

我有一个这样的小部件树:

SingleChildScrollView
Column
Container
ListView(or GridView)

问题是,当我的小部件树如上所示时,它会给我错误的

需要油漆

所以我改变了我的小部件树,像这样:

Column
Container
ListView(or GridView)

但是在这种情况下,ListView 或 GridView 部分会单独滚动,我希望整个小部件树都能滚动。你觉得我是怎么做到的?

56265 次浏览

You could use your first widget-tree and apply the following changes:

  1. In every ListView and GridView set shrinkWrap: true. This fixes the error message you were getting.
  2. In every ListView and GridView set physics: NeverScrollableScrollPhysics(). This disables the scroll on them and new you can only scroll on the SingleChildScrollView

Set primary to false in your ListView.

ListView(
primary: false,
),

That should prevent it from scrolling separately.

For me, setting primary to false and shrinkWrap to true worked.

ListView(
primary: false,
shrinkWrap: true,
),

As suggested by other answers, you can do that by setting shrinkWrap: true, physics: NeverScrollableScrollPhysics(), but building a shrinkwrapped listview is more expensive than building a normal listview, I think it will be a good idea to use a map() on the list.

Column(
children: <Widget>[
...itemList.map((item) {
return Text(item);
}).toList(),
],
),

Why it is happening?

It happens because Column and ListView both take the entire space of screen individually which is there default behavior.

How to solve the problem?

To solve the above problem we have to disable scrolling of Listview, This can be possible by shrinkWrap and physics property

shrinkWrap:true - It forces ListView to take only the required space, not the entire screen.

physics: NeverScrollableScrollPhysics() - It disables scrolling functionality of ListView, which means now we have only SingleChildScrollView who provide the scrolling functionality.

Code:

SingleChildScrollView
Column
Container
ListView(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
//...
)

https://medium.com/flutterworld/flutter-problem-listview-vs-column-singlechildscrollview-43fdde0fa355

Note: Above ListView behaviour will be also applied for GridView.

I am using nested Listviews and this helped me. Add these lines in all of your ListviewBuilders

ListView(
shrinkWrap: true,
primary: false,
),

using this inside listview works fine for me.

physics: NeverScrollableScrollPhysics(),


shrinkWrap: true,

This will work like a charm.

Column(
children: itemList.map((item) {
return Text(item);
}).toList(),
),