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,
)
,
You can add some code like this
ListView.builder{
shrinkWrap: true,
}
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
or Flexible
if you want to allow ListView
to take up entire left space in Column
.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
Use SizedBox
if you want to restrict the size of ListView
to a certain height.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
Use shrinkWrap
, if your ListView
isn't too big.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)
I used this code to fix the issue of displaying items in the horizontal list.
new Container(
height: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: array.length,
itemBuilder: (context, index){
return array[index];
},
),
],
),
);
Wrap your ListView in an Expanded widget
Expanded(child:MyListView())
Placing your list view in a Flexible widget may also help,
Flexible( fit: FlexFit.tight, child: _buildYourListWidget(..),)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With