flutter_swiper 是一款超级棒的轮播图框架,也为我们提供了不同类型的分页指示器,奈何公司UI设计人员各有各的想法,没办法,最后还是要自定义才能解决问题
先看一眼设计图吧
找了很多文章,大部分文章都是要修改 flutter_swiper 的flutter_page_indicator源文件,并涉及到Canvas, 个人感觉有些复杂。
自己尝试找了找有没有不修改源码的方法,最终发现 使用 SwiperPagination+SwiperCustomPagination方式,能够解决问题
直接贴代码:
我们需要先创建一个自定义的分页指示器类型
class NLIndicator extends StatelessWidget with NLBaseMixin {
var _currentIndex;
var _count;
NLIndicator(this._currentIndex, this._count);
@override
Widget build(BuildContext context) {
return Container(
width: dp(150),
margin: EdgeInsets.only(right: dp(34)),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: List.generate(_count, (index){
return _currentIndex == index ? Container(
width: dp(24),
height: dp(8),
margin: EdgeInsets.only(right: dp(8)),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(4)
),
) : Container(
width: dp(8),
height: dp(8),
margin: EdgeInsets.only(right: dp(8)),
decoration: BoxDecoration(
color: hexColor(0xffffff, alpha: 0.5),
borderRadius: BorderRadius.circular(20)
),
);
}),
),
);
}
}
后面调用
Swiper(
itemBuilder: (BuildContext context, int index) {
return Container(
padding: EdgeInsets.symmetric(horizontal: dp(34)),
child: ClipRRect(
borderRadius: BorderRadius.circular(dp(24)),
child: CachedNetworkImage(
imageUrl: list[index],
fit: BoxFit.cover,
placeholder: (context, ulr) => NLSkeletonContainers(),
),
),
);
},
onIndexChanged: onIndexChanged,
onTap: onTap,
itemWidth:
MediaQuery.of(navigatorKey.currentState.overlay.context).size.width,
itemCount: list.length,
pagination: SwiperPagination(
alignment: Alignment.bottomRight,
builder: SwiperCustomPagination(
builder: (BuildContext context, SwiperPluginConfig config) {
return NLIndicator(config.activeIndex, list.length);
})),
layout: SwiperLayout.DEFAULT,
),
重点在 pagination
最终我们就能得到想要的效果了