flutter轮播图控件根据图片高度动态调整图高度
1.图片链接资源需要带有宽高信息
例如:https://zmkx.oss-cn-hangzhou.aliyuncs.com/oss/folder/atui2024-12-231734938007236a30cb975297842d0b3d2b82e4ec7f72b7unhmlcaj4el.jpg?Size=1080x2388
在链接中拼接?Size=1080x2388携带。
2.获取到数据后切割出宽高
List<Map<String, dynamic>> _swiperDataUrl; //轮播图数据源
/*
* 计算轮播图图片高度
* articlePic: 请求接口获取到的图片集合
* */
_maxSwiperHeight(List articlePic) {
if(articlePic == null || articlePic.isEmpty){
return;
}
List<Map<String, dynamic>> _swiperHeight = [];
double width;
double height;
//切割出图片宽高信息
articlePic.forEach((element) {
if(element.type == 'P'){
String url = element.url;
List<String> strList =
url.contains('?Size=')
? url.split('?Size=')
: url.contains('?size=')
? url.split('?size=')
: null;
if (strList != null && strList.length >= 1) {
url = strList.last;
List<String> size = url.split('x');
width = double.parse(size[0]);
height = double.parse(size[1]);
double screenWidth = _articleDetail.redirectFlag == 1
? getScreenWidth() - 40
: getScreenWidth();
//配置每张图片显示时轮播控件需要的高度
if (width > screenWidth) {
height = height / (width / screenWidth);
} else {
height = height * (screenWidth / width);
}
if(height > screenWidth * 1.3){
height = screenWidth * 1.3;
}
} else {
height = 500.h;
}
// 轮播图资源链接
_swiperHeight
.add({"url": element.url, "height": height.ceilToDouble(),'type':'P'});
setState(() {
_swiperDataUrl = _swiperHeight;
});
}
});
}
3.显示轮播图
int _currentImageIndex = 0;
_swiperView(){
return
// 图片
_articleDetail.articleType == 1
? _swiperDataUrl!=null
? AnimatedContainer(
duration: Duration(milliseconds: 300),
width: winWidth(context: context),
height: _swiperDataUrl[_currentImageIndex]['height'],
color: Colors.white,
child: Swiper(
controller: _swiperController,
itemCount: _swiperDataUrl.length,
loop: false,
autoplay: false,
onIndexChanged: (index){
setState(() {
_currentImageIndex = index;
});
},
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
_toViewBigPhoto(
context, _articleDetail.articlePic, index);
},
child: _swiperDataUrl[index]['type'] == 'P'?
CachedNetworkImage(
fit: BoxFit.cover,
imageUrl: _swiperDataUrl[index]['url'],
width: double.infinity,
):_swiperDataUrl[index]['type'] == 'V'?
ClipRRect(
child: ArticleDetailVideoPage(
_articleDetail.articlePic[index].url,
mute: true,
toFullScreenPage: false,
clickVideoCallback: _toOriginalArticle,
),
)
:SizedBox(),
);
},
pagination: SwiperPagination(
builder: DotSwiperPaginationBuilder(
size: 7,
color: Color(0xff999999),
activeColor: Color(0xffffffff))),
)
) : SizedBox()
// 视频
: _articleDetail.articleType == 2
? _videoView()
: SizedBox();
}