有没有办法自动播放 CarouselView 中的项目?
CarouselView(
elevation: 2,
itemSnapping: true,
itemExtent: 330,
shrinkExtent: 100,
children: [
_CardLayout(index: 1, label: "assets/images/image1.jpg",color: Colors.blue),
_CardLayout(index: 2, label: "assets/images/image2.jpg",color: Colors.green),
_CardLayout(index: 3, label: "assets/images/image3.jpg",color: Colors.red),
])
我尝试检查 CarouselView 的选项,似乎没有可用的属性,例如显示幻灯片指示器和自动播放,如 flutter_carousel_widget
中的属性提前致谢。
新的 CarouselView
小部件中没有一个直接的选项来
自动播放项目。但是,您可以通过手动控制
CarouselController
来实现此功能。这是一个例子:
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: MyApp(),
),
);
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final CarouselController _carouselController;
final _itemExtent = 330.0;
final _autoPlayDuration = const Duration(seconds: 4);
@override
void initState() {
super.initState();
_carouselController = CarouselController();
// Animates to the next item every 4 seconds
Timer.periodic(
_autoPlayDuration,
(_) => _animateToNextItem(),
);
}
@override
void dispose() {
_carouselController.dispose();
super.dispose();
}
void _animateToNextItem() {
_carouselController.animateTo(
_carouselController.offset + 330,
duration: const Duration(milliseconds: 500),
curve: Curves.linear,
);
}
@override
Widget build(BuildContext context) {
return Center(
child: SizedBox(
height: 300,
child: CarouselView(
elevation: 2,
itemSnapping: true,
shrinkExtent: 100,
itemExtent: _itemExtent,
controller: _carouselController,
children: List.generate(
10,
(index) => Container(
color: index.isOdd ? Colors.red : Colors.blue,
child: Center(
child: Text('Item $index'),
),
),
),
),
),
);
}
}
在此示例中,
Timer
用于通过调整 CarouselController
每 4 秒自动移动到下一个项目。这模仿了“自动播放”行为。动画duration
和curve
可以根据需要定制。