实际开发中,广告轮播图是必不可少的,下面就用插件来实现一下。
效果图如下:
添加插件:
flutter_swiper: ^1.1.6
导入包:
import 'package:flutter_swiper/flutter_swiper.dart';
添加代码,代码中有注释,图片适配,自动轮播,设置指示器等:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<HomePage> {
List _imageUrl = [
'https://upload-images.jianshu.io/upload_images/5809200-a99419bb94924e6d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240',
'https://upload-images.jianshu.io/upload_images/5809200-736bc3917fe92142.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240',
'https://upload-images.jianshu.io/upload_images/5809200-7fe8c323e533f656.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240',
'https://upload-images.jianshu.io/upload_images/5809200-48dd99da471ffa3f.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240',
'https://upload-images.jianshu.io/upload_images/5809200-4de5440a56bff58f.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240',
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Container(
height: 160, //高度
child: Swiper(
itemCount: _imageUrl.length, //广告图片长度
autoplay: true, //自动播放
itemBuilder: (BuildContext context,int index){
return Image.network(
_imageUrl[index],
fit: BoxFit.fill, //图片适配方式
);
},
//设置指示器
pagination: SwiperPagination(),
),
)
],
),
),
);
}
}