Flutter CarouselSlider不使用GetX如何获取索引值传递给DotsIndicator
解决方法
使用StatefulWidget维护轮播当前索引状态,通过CarouselSlider自带的onPageChanged回调获取实时索引更新状态即可,无需第三方状态管理。
具体实现步骤:
- 第一步:在当前页面的State类中定义索引存储变量
class _YourPageState extends State<YourPage> { // 存储轮播当前索引 int _currentIdx = 0; // 其余原有代码保持不变 }
- 第二步:给
CarouselOptions添加onPageChanged回调,更新索引状态
CarouselSlider.builder( options: CarouselOptions( viewportFraction: 1, // 新增页面切换回调 onPageChanged: (index, reason) { setState(() { _currentIdx = index; }); }, ), itemCount: 10, itemBuilder: (context, idx, realIndex) { return buildImage(articles, urlImages[idx], idx, context); }, ),
- 第三步:将
DotsIndicator的position赋值为状态中存储的索引
DotsIndicator( dotsCount: 10, position: _currentIdx.toDouble(), decorator: DotsDecorator( size: const Size.square(6.0), activeSize: const Size(22.0, 6.0), activeShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5.0)), activeColor: Colors.blue, spacing: const EdgeInsets.all(3.0), ), ),
onPageChanged会在轮播页面切换时自动触发,每次切换都会返回当前最新的索引值,通过setState更新状态后,和轮播平级的指示器会自动重绘获取最新索引,不会出现指示器跟随轮播滑动的问题。
内容的提问来源于stack exchange,提问作者gegentierversuche
相关产品推荐
相关产品推荐

