简体   繁体   中英

flutter: space between horizontal listView items

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:

  • First (recommended) , replace your 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.

  • Second option , if you really need to keep the 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM