Flutter: RenderBox was not laid out
The problem is that you are placing the ListView
inside a Column/Row. The text in the exception gives a good explanation of the error.
To avoid the error you need to provide a size to the ListView
inside.
I propose you this code that uses an Expanded
to inform the horizontal size (maximum available) and the SizedBox
(Could be a Container) for the height:
new Row(
children: <Widget>[
Expanded(
child: SizedBox(
height: 200.0,
child: new ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: products.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(products[index]);
},
),
),
),
new IconButton(
icon: Icon(Icons.remove_circle),
onPressed: () {},
),
],
mainAxisAlignment: MainAxisAlignment.spaceBetween,
)
,
Reason for the error:
Column
tries to expands in vertical axis, and so does the ListView
, hence you need to constrain the height of ListView
.
Solutions
Use either
Expanded
orFlexible
if you want to allowListView
to take up entire left space inColumn
.Column( children: <Widget>[ Expanded( child: ListView(...), ) ], )
Use
SizedBox
if you want to restrict the size ofListView
to a certain height.Column( children: <Widget>[ SizedBox( height: 200, // constrain height child: ListView(), ) ], )
Use
shrinkWrap
, if yourListView
isn't too big.Column( children: <Widget>[ ListView( shrinkWrap: true, // use it ) ], )
use shrinkWrap: true
,
With shrinkWrap: true, you can change this behavior so that the ListView only occupies the space it needs (it will still scroll when there more items). If you set it to true, the list will wrap its content and be as big as it children allows it to be.
like this.
ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
.........
}
)
You can add some code like this
ListView.builder{
shrinkWrap: true,
}