Flutter:水平ListView项之间的间距

11

我正在尝试在Flutter中实现水平列表视图,目前功能正常,但产品之间的距离太紧密了,是否有办法在它们之间添加空间?

提前感谢。

 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])),
            );
          }
        },
                 )))])
              ],
            ),
          ),
          

2个回答

24

为了在项目之间添加间距,有两种解决方案:

  • 首选(推荐),用 ListView.separated 替换你的 ListView.builder,并添加标签 separatorBuilder

例如,如果要在每个项目之间添加空格:

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])),
);

您可以用Divider或任何您需要的小部件来替换SizedBox。

这种解决方案的优点是它将在每个项目之间添加分隔符,并且不会在末尾添加多余的分隔符。

  • 第二个选项,如果您确实需要保留ListView.builder,请在AlAinPdtItem小部件中包装一个填充(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])),
      ),
);

这样做的缺点是,填充将被添加到每个项目上,这意味着最后一个项目后面会有额外的空间(在本例中为10像素)。


谢谢您的回答,我尝试了两种方法,但产品仍然相互附着,并且它们之间没有空格。 - raya
我尝试了两种方法,它们都运行良好。你有一个最小的代码示例可以复现吗? - Lucie
我在你的答案中添加了完全相同的代码,但好像什么也没有改变:\ - raya
如果我无法重现您的问题,我就无法提供帮助。请提供一个用于重现问题的代码示例。例如,我没有AlAinPdtItem类,或者我看不到httpService在哪里定义。 - Lucie

1

如果您不想使用 ListView.separated(),您可以像这样添加自己的间距:

ListView(
  children: myListTiles.expand((tile) => [tile, SizedBox(height: 12)]).toList()..removeLast()
)

(编辑:如果您的列表非空,则.. removeLast()才起作用,因此可能不是完美的解决方案。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接