Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical ListView inside horizontal SingleChildScrollView

I need to build a page with lists of objects that are grouped in a single line. This needs to be scrolled both vertically (to show more groups) and horizontally (to show groups children). The vertical and horizontal scroll needs to move the items altogether. Something like this: https://gph.is/g/46gjW0q

I'm doing this with this code:

Widget _buildGroups() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Container(
        width: 2000,
        child: ListView.builder(
          scrollDirection: Axis.vertical,
          itemCount: boardData.length,
          itemBuilder: (context, index) {
            return Row(children: _buildSingleGroup(index));
          },
        ),
      ),
    );
}

List<Widget> _buildSingleGroup(int groupIndex) {
    return List.generate(...);
}

I need this to be horizontally dynamic but here, as you can see, I need to set a width cause otherwise an error occurs:

══════════════════ Exception caught by rendering library ═════════════════════
The following assertion was thrown during performResize()
Vertical viewport was given unbounded width.

Viewports expand in the cross axis to fill their container and constrain their 
children to match their extent in the cross axis. In this case, a vertical 
viewport was given an unlimited amount of horizontal space in which to expand.

I tried to set "shrinkWrap: true" in the ListView but the result gives another error:

Failed assertion: line 1629 pos 16: 'constraints.hasBoundedWidth': is not true.

So how do you do this with a dynamical ListView width?

like image 573
Davide Bicego Avatar asked Nov 16 '22 22:11

Davide Bicego


1 Answers

The error happens because when ListView tries to get height from its parent to fill the entire height, the parent returns infinity height because SingleChildScrollView doesn't have fixed container height value. To fix that issue you need to limit the height value. For example, I used SizedBox to specify height for ListView.

The following code works for me.

SingleChildScrollView(
  child: Column(
    mainAxisSize: MainAxisSize.min,
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      SizedBox(
        height: 120, // <-- you should put some value here
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: items.length,
          itemBuilder: (context, index) {
            return Text('it works');
          },
        ),
      ),
    ],
  ),
);
like image 134
TheMisir Avatar answered Jun 08 '23 01:06

TheMisir