导入要使用的轮播图片
- List<String> imagesa = [
- "assets/images/car_qidian.jpg",
- "assets/images/car_bg.jpg",
- "assets/images/car_bg.jpg",
- "assets/images/car_bg.jpg",
- "assets/images/car_bg.jpg",
- "assets/images/car_bg.jpg",
- "assets/images/car_bg.jpg",
- "assets/images/car_bg.jpg",
- "assets/images/car_bg.jpg",
- "assets/images/car_bg.jpg"
- ];
- late PageController _controller;
- Timer? _timer,
-
- //背景图动画
- void startTimer() {
- _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
- if (_controller.hasClients) {
- if (_controller.page!.round() >= imagesa.length - 1) {
- _controller.jumpToPage(0);
- } else {
- _controller.nextPage(
- duration: const Duration(seconds: 1),
- curve: Curves.linear,
- );
- }
- }
-
- });
- }
-
- void pauseTimer() {
- _timer?.cancel();
- }
-
- void restartTimer() {
- _timer?.cancel();
- startTimer();
- }
-
- // 背景使用
- void _onPageChanged() {
- int newIndex = _controller.page!.round() % imagesa.length;
- if (newIndex != _currentPage) {
- setState(() {
- _currentPage = newIndex;
- });
- }
- }
然后在initState里面初始化一下
- @override
- void initState() {
- super.initState();
- startTimer();
- }
在dispose里面去掉
- @override
- void dispose() {
- _controller.dispose();
- _timer?.cancel();
- super.dispose();
- }
最后在你需要的地方加入下面代码就行了
- //背景图
- SizedBox(
- height: 750.h,
- child: PageView.builder(
- physics: const NeverScrollableScrollPhysics(),
- controller: _controller,
- itemBuilder: (context, index) {
- final imageIndex = index % imagesa.length;
- return Image.asset(
- imagesa[imageIndex],
- width: double.infinity,
- height: 750.h,
- fit: BoxFit.fitHeight,
- gaplessPlayback: true,
- );
- },
- ),
- ),