i'm trying to implement horizontal list view in flutter and it's working good but products are too attached to each others, is there a way to put space between them ? thanks in advance
Row(
children: <Widget>[
Expanded(
child: SizedBox(
child: FutureBuilder(
future: httpService.getProducts(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text('Loading...'),
),
);
}
else if (snapshot.data.length == 0){
return Container(
child: Center(
child: Center(
child: Text('No offers'),
),
),
);
} else {
return ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (ctx, i) => (AlAinPdtItem(
title: snapshot.data[i].title,
imgUrl: snapshot.data[i].imgUrl,
price: snapshot.data[i].price,
pdt2: snapshot.data[i])),
);
}
},
)))])
],
),
),
To add space between the items, these are 2 solutions:
ListView.builder
by a ListView.separated
, and add the tag separatorBuilder
.Example, to add a space between each item:
return ListView.separated(
separatorBuilder: (BuildContext context, int index) {
return SizedBox(height: 3);
},
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (ctx, i) => (AlAinPdtItem(
title: snapshot.data[i].title,
imgUrl: snapshot.data[i].imgUrl,
price: snapshot.data[i].price,
pdt2: snapshot.data[i])),
);
You can replace the SizedBox by a Divider, or any widget you need. The advantage of this solution is that it will add a separator between each item, and won't add an extra one at the end.
ListView.builder
, wrap your widget AlAinPdtItem
in a Padding:return ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (ctx, i) => (Padding(
padding: EdgeInsets.fromLTRB(0, 0, 0, 10),
child: AlAinPdtItem(
title: snapshot.data[i].title,
imgUrl: snapshot.data[i].imgUrl,
price: snapshot.data[i].price,
pdt2: snapshot.data[i])),
),
);
The drawback of this is that the Padding will be added on each item, which means that the last item will have an extra space (10px in this case) afterwards.
Or if you don't want to use ListView.separated()
, you can add your own spacings like this:
ListView(
children: myListTiles.expand((tile) => [tile, SizedBox(height: 12)]).toList()..removeLast()
)
(Edit: The ..removeLast()
only works if your list is non-empty, so maybe not the perfect solution)
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