Flutter 实现 「图片轮播」效果
2019-03-04 本文已影响21人
黑键手记
拖了好几天,终于要实现 「图片轮播」效果了,是不是很激动。
前几天专门学习的 Timer
、PageView
还有没有印象呢?如果没有的话,可以再回去看看哦。
我们先来看下效果动图

就是在 之前PageView
的基础上,添加了自动轮播效果。
那么,废话少说,开始吧。
一、准备数据源
很简单,准备5张图片,同样从小米官网偷


注意到没有,除了声明了 5 张图片之外,还单独提供了一个 realImgs
的列表。他的作用很关键,决定了用户的体验哦。
这样做的目的是,「欺骗视觉」
在第一个位置增加 「real 最后一张图片」; 在最后的位置增加「real 第一张图片」,让「real 图片长度」 变成了 「real 图片长度 + 2。
这样,只需在滑动 pageview 的时候,当滑到「real 数组最后一张」的时候,强制显示「扩容数组的第一个元素」;
当手动滑动到「real 数组第一张」的时候,强制显示「扩容数组的最后的元素」。
这样一来,「循环轮播」的效果就出来了。
二、准备单个页面布局
很简单,直接贴代码了,注意,我特意用 Text 标识出真实的 图片的索引,好明白「循环轮播」的原理

三、定义循环的 Timer

先不用看注释,如果有疑惑,再看注释
四、准备 PageView 中的必要的属性





然后因为还需要滚动监监听,所以需要再准备通知

最后,把我们创建的 PageView 用 NotificationListener 包裹起来即可,像这样
//创建类viewpager
Widget Pager(constraints, callback) {
return new NotificationListener(
child: new PageView.custom(....
五、这样,在 开始的 initState 中的 Timer 的推动下,PageView 就会开始循环轮播,然后在 PageView 的 页面监听的驱动以及通知的共同作用下,营造出像是在 ‘无限轮播’ 的假象。
Bingo!总结一下。
Timer
PageView
PageController
NotificationListener
PageScrollPhysics