I\'m trying to create a horizontal scrolling list of items in Flutter, and I want that list to only take up the necessary height based on its children. By design “List
Use ConstrainedBox to set minHeight and maxHeight
ConstrainedBox(
constraints: new BoxConstraints(
minHeight: 35.0,
maxHeight: 160.0,
),
child: new ListView(
shrinkWrap: true,
children: <Widget>[
new ListItem(),
new ListItem(),
],
),
)
Wrapping the widget by Column with mainAxisSize: MainAxisSize.min worked for me. You can try to change the height here.
var data = [
{'name': 'Shopping', 'icon': Icons.local_shipping},
{'name': 'Service', 'icon': Icons.room_service},
{'name': 'Hotel', 'icon': Icons.hotel},
{'name': 'More', 'icon': Icons.more}
];
new Container(
constraints: new BoxConstraints(
minHeight: 40.0,
maxHeight: 60.0,
),
color: Colors.transparent,
child: new ListView(
scrollDirection: Axis.horizontal,
children: data
.map<Widget>((e) => Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Container(
width: 40,
height: 50, // try to change this.
color: Colors.transparent,
margin: EdgeInsets.only(right: 20, left: 4),
child: ClipOval(
child: Container(
padding: EdgeInsets.all(4),
color: Colors.white,
child: Icon(
e["icon"],
color: Colors.grey,
size: 30,
),
),
),
),
],
))
.toList(),
));
Just set shrink property of ListView to true and it will fit the space rather than expanding.
Example:
ListView(
shrinkWrap: true, //just set this property
padding: const EdgeInsets.all(8.0),
children: listItems.toList(),
),
I'm using a horizontal listview builder of container so to stop the Container for taking the full height i just wrapped it with Center and it worked perfectly.
itemBuilder: (context, i){
return Center(child: word_on_line(titles[i]));
}
Use Expanded
Expanded(
child:ListView.separated(
shrinkWrap: true,
padding: EdgeInsets.all(10),
separatorBuilder: (BuildContext context, int index) {
return Align(
alignment: Alignment.centerRight,
child: Container(
height: 0.5,
width: MediaQuery.of(context).size.width / 1.3,
child: Divider(),
),
);
},
itemCount: dataMasterClass.length,
itemBuilder: (BuildContext context, int index) {
Datum datum = dataMasterClass[index];
return sendItem(datum);
},)
) ,
As far as I understand, you can't have a horizontal ListView inside a vertical ListView and have its height dynamically set. If your requirements allow (no infinite scrolling, small amount of elements, etc), you could use a SingleChildScrollView instead.
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [...],
),
);