Flutter, how to set max height to list view items

Viewed 3629

what I have tried is below.

         SizedBox(
           width: MediaQuery.of(context).size.width * 0.88,
           height: MediaQuery.of(context).size.height * 0.42,
             child: ListView.builder(
                   itemCount: 10,                          
                   itemBuilder: (BuildContext context, int index) {
                            return _buildListItem();
                         }),
                   )

and the list widget

 Widget _buildListItem() {
    return ConstrainedBox(
      constraints: BoxConstraints(
        minHeight: 20,
          maxHeight: 120),
       child:Container(child:Text("Looooongggg textttttttttt 
              the text size is alwayysss different "),
       ),}

I want to make the list view item size dynamically, but also the max height is fixed at 120. In other words, no matter how long the text is, the container also wants to be to not go up to 120 or more.

This code always shows me only max height containers. No matter how short the letters are,

how could I achieve that?

3 Answers

Try IntrinsicHeight widget

Widget _buildListItem() {
    return ConstrainedBox(
      constraints: BoxConstraints(
        minHeight: 20,
          maxHeight: 120),
       child: IntrinsicHeight(child:Container(child:Text("Looooongggg textttttttttt 
              the text size is alwayysss different "),
       )),}

You can do it by setting the scroll physics to NeverScrollablePhysics. By doing so List View would take enough height so that all its children can fit into it. For example:-

    ...
    ListView.builder(
      physics:NeverScrollableScrollPhysics(),//this line would the change                               
      itemCount: 10,                          
      itemBuilder: (BuildContext context, int index) {
              return _buildListItem();
            }),
           ),
    ...

Use Container and assign min, max-height to BoxConstraints

Container(
        child: ListView.builder(itemBuilder: (BuildContext context, index) {
            return Container(
              constraints: BoxConstraints(minHeight: 20, maxHeight: 40),
              color: Colors.red,
              child: Divider(),
            );
        }, itemCount: itemsList.length,),
      ),

Output:

enter image description here

Related