Flutter: Scrollable Column child inside a fixed height Container

912

Solution 1

Wrap your ListView with Expanded. Remove your SingleChildScrollView as ListView has its own scrolling behaviour. Try as follows:

Container(
height: 250,
child: Column(children: <Widget>[
    Text('Title'),
    Divider(),
    Expanded(
      
        child: ListView.builder(
            shrinkWrap: true,
            itemCount: 15,
            itemBuilder: (BuildContext context, int index) {
                return Text('abc');
            }
        ),
    
    )
]
))

Solution 2

Wrap your ListView.builder() widget inside a SizedBox() widget and specify available height after accommodating Title() widget.

Container(
    height: 250,
    child: Column(children: <Widget>[
        Text('Title'),
        Divider(),
        SizedBox(
            height: 200, // (250 - 50) where 50 units for other widgets
            child: SingleChildScrollView(
                child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: 15,
                    itemBuilder: (BuildContext context, int index) {
                        return Text('abc');
                    }
                )
            )
        )
    ]
)

You can also use Container() widget instead SizedBox() widget but only if needed. SizedBox() is a const constructor where Container() widget is not, so SizedBox() allows the compiler to create more efficient code.

Share:
912
Gabi
Author by

Gabi

Updated on December 27, 2022

Comments

  • Gabi
    Gabi over 1 year

    I have several containiers inside a ListView which will result in a scrollable content within a page. Each container has a Column as child and within the Column I have a title and a divider, then the actual content.


    I want one of the container to be something like:

    Title
    --------- (divider)
    Scrollable content (most likely a ListView)
    

    What I have so far:

    Container(
        height: 250,
        child: Column(children: <Widget>[
            Text('Title'),
            Divider(),
            SingleChildScrollView(
                child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: 15,
                    itemBuilder: (BuildContext context, int index) {
                        return Text('abc');
                    }
                )
            )
        ]
    )
    

    The thing is that I want the container to have a specific height, but I get an overflow pixel error.

    enter image description here

    • Minh Nguyên
      Minh Nguyên almost 3 years
      try wrap listview.builder in Expanded
    • Gabi
      Gabi almost 3 years
      Thank you @MinhNguyên, that worked wonderful. I will set the Nbh's answer as the best answer just for others to see it more clearly and quickly, but you solved the problem. :)
    • Minh Nguyên
      Minh Nguyên almost 3 years
      can you give me 'useful' :)