今天我们来介绍一款Flutter的第三方组件库——flutter_swiper。
使用代码如下:
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Map> _swiperDataSources = [
{
"imgUrl":
"http://pic60.nipic.com/file/20150129/6448355_204110337000_2.jpg",
"linkUrl":
"http://pic60.nipic.com/file/20150129/6448355_204110337000_2.jpg"
},
{
"imgUrl": "http://pic13.nipic.com/20110409/7119492_114440620000_2.jpg",
"linkUrl": "http://pic13.nipic.com/20110409/7119492_114440620000_2.jpg"
},
{
"imgUrl":
"http://gss0.baidu.com/-fo3dSag_xI4khGko9WTAnF6hhy/lvpics/w=600/sign=1350023d79899e51788e391472a5d990/b21bb051f819861810d03e4448ed2e738ad4e65f.jpg",
"linkUrl":
"http://gss0.baidu.com/-fo3dSag_xI4khGko9WTAnF6hhy/lvpics/w=600/sign=1350023d79899e51788e391472a5d990/b21bb051f819861810d03e4448ed2e738ad4e65f.jpg"
},
{
"imgUrl":
"http://img4.cache.netease.com/photo/0001/2010-04-17/64EFS71V05RQ0001.jpg",
"linkUrl":
"http://img4.cache.netease.com/photo/0001/2010-04-17/64EFS71V05RQ0001.jpg"
}
];
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
Container(
width: double.infinity, //宽度自适应
child: //AspectRatio可以调整子元素的宽高比
AspectRatio(
aspectRatio: 16 / 9, //子元素的宽高比
child: Swiper(
itemBuilder: (BuildContext context, int index) {
return new Image.network(
_swiperDataSources[index]["imgUrl"],
fit: BoxFit.fill,
);
},
itemCount: _swiperDataSources.length,
//分页指示器
pagination: SwiperPagination(
alignment: Alignment.bottomLeft,//分页指示器的位置
margin: EdgeInsets.all(10),//分页指示器与容器边框的距离
builder: SwiperPagination.fraction,//分页指示器样式
),
//控制按钮
control: SwiperControl(
iconPrevious: Icons.arrow_back_ios,//上一页的IconData
iconNext: Icons.arrow_forward_ios,//下一页的IconData
color: Colors.pink,//控制按钮的颜色
size: 30.0,//控制按钮的大小
padding: EdgeInsets.all(5),//控制按钮与容器的距离
),
scrollDirection: Axis.horizontal,//滚动方向(默认是水平)
loop: false,//是否开启无线轮播模式
index: 1,//初始的下标位置
autoplay: true,//是否自动播放
//当用户手动拖拽或者自动播放引起下标改变的时候调用
onIndexChanged: (index){
// print(index);
},
//当用户点击某个轮播的时候调用
onTap: (index){
print("用户点击$index");
},
duration: 300,//动画时间,单位是毫秒
),
),
)
],
),
);
}
}运行效果如下:

关于flutter_swiper这个Flutter的第三方轮播图库,我有以下几点需要说明:
1,我这里只是介绍了 flutter_swiper 这个第三方库的基本用法,还有一些其他的效果我在本文中并没有涉及,以后大家用到的时候可以去仔细读一下flutter_swiper官方Demo还有使用说明,那里面有详细介绍,并且有代码示例,大家找到自己满意的效果,然后把对应的代码直接拷贝过来用即可。
2,本文的目的并不是让大家记住flutter_swiper的各个属性和用法,目的是告诉我自己以及看到这篇文章的各位,在Flutter中,如果要实现轮播图的效果,flutter_swiper这个第三方库很好用,推荐给大家。
3,以后如果有轮播图的需求,可以找到flutter_swiper这个第三方库的文档,仔细通读一遍文档,找到自己中意的效果,然后再去写代码。
4,总而言之,如果你的Flutter项目中需要使用轮播图,那就选择flutter_swiper这个第三方库吧!~
以上。