Flutter Swiper仅单条数据时如何隐藏两侧溢出图片且不改变卡片宽度

解决方案
侧边出现的重复图片是flutter_swiper默认开启轮播循环导致的,单条数据时会自动生成前后重复的副本填充侧边,你可以根据数据长度动态配置Swiper参数实现需求,不需要改动原有卡片尺寸:
核心修改点是仅在数据条数大于1时开启循环和自动轮播,单条数据时关闭即可消除侧边重复图。
修改后的代码参考:
Swiper( // 动态配置:仅数据条数>1时开启自动轮播 autoplay: dataPromo.length > 1, // 动态配置:仅数据条数>1时开启循环,单条时关闭就不会生成侧边重复副本 loop: dataPromo.length > 1, itemBuilder: (BuildContext context, int index) { return InkWell( child: Card( margin: const EdgeInsets.only(bottom: 30), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20) ), child: ClipRRect( child: CachedNetworkImage( imageUrl: dataPromo[index].bannerPath, fit: BoxFit.fill, ) ) ), ); }, itemCount: dataPromo.length, viewportFraction: 0.8, scale: 0.9, ),
如果修改后单条数据的卡片尺寸出现变化,你可以再动态调整viewportFraction和padding属性,保持原有尺寸完全不变:
Swiper( autoplay: dataPromo.length > 1, loop: dataPromo.length > 1, // 单条时添加水平padding,保持卡片宽度和原0.8视口占比一致 padding: dataPromo.length == 1 ? EdgeInsets.symmetric(horizontal: MediaQuery.of(context).size.width * 0.1) : EdgeInsets.zero, itemBuilder: (BuildContext context, int index) { return InkWell( child: Card( margin: const EdgeInsets.only(bottom: 30), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20) ), child: ClipRRect( child: CachedNetworkImage( imageUrl: dataPromo[index].bannerPath, fit: BoxFit.fill, ) ) ), ); }, itemCount: dataPromo.length, // 单条时视口占比设为1,配合padding实现卡片尺寸不变 viewportFraction: dataPromo.length > 1 ? 0.8 : 1, scale: 0.9, ),
内容的提问来源于stack exchange,提问作者Eggy
相关产品推荐
相关产品推荐

