You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中为ListWheelScrollView.useDelegate添加点击触发的数秒自动滚动功能

解决方案

完全可以实现该效果,核心是通过FixedExtentScrollController绑定ListWheelScrollView,配合计时器控制滚动逻辑即可,具体实现步骤如下:

第一步:定义所需控制器与变量

在你的State类中声明滚动控制器和计时器:

// 滚动控制器,绑定ListWheelScrollView
final FixedExtentScrollController _scrollController = FixedExtentScrollController();
// 控制自动滚动的计时器
Timer? _autoScrollTimer;
// 你要滚动的总时长,这里示例为3秒
final int _scrollDuration = 3;
// 每两次滚动的间隔,控制滚动速度
final Duration _scrollInterval = const Duration(milliseconds: 100);

第二步:修改ListWheelScrollView组件,绑定控制器

给你的ListWheelScrollView.useDelegate添加controller参数:

return Container(
  height: 125,
  width: ScreenSize.width * 0.3,
  // 绑定滚动控制器
  child: ListWheelScrollView.useDelegate(
    controller: _scrollController,
    diameterRatio: 1,
    squeeze: 1.8,
    itemExtent: 75,
    physics: const FixedExtentScrollPhysics(),
    onSelectedItemChanged: (index) => print(index),
    childDelegate: ListWheelChildLoopingListDelegate(
      children: List<Widget>.generate(
        slotNames.length,
        (index) => Padding(
          padding: const EdgeInsets.all(3.0),
          child: Container(
            decoration: BoxDecoration(
              border: Border.all(
                color: Colors.blue,
              ),
              borderRadius: BorderRadius.circular(10.0),
            ),
            child: Image.asset(
              "assets/$index.png",
              width: double.infinity,
              height: double.infinity,
            ),
          ),
        ),
      ),
    ),
  ),
);

第三步:编写自动滚动触发方法

给按钮添加点击事件,调用如下方法即可启动自动滚动:

void _startAutoScroll() async {
  // 如果已经在滚动,先停止之前的滚动
  if(_autoScrollTimer?.isActive ?? false) {
    _autoScrollTimer?.cancel();
  }
  // 记录滚动的起始时间
  final startTime = DateTime.now();
  _autoScrollTimer = Timer.periodic(_scrollInterval, (timer) {
    // 判断是否达到总滚动时长
    if(DateTime.now().difference(startTime).inSeconds >= _scrollDuration) {
      timer.cancel();
      // 可选:滚动结束后固定到某个位置,比如随机停在某个item上
      // _scrollController.animateToItem(
      //   Random().nextInt(slotNames.length), 
      //   duration: const Duration(milliseconds: 300), 
      //   curve: Curves.easeOut
      // );
      return;
    }
    // 每次滚动到下一个item,因为是循环列表,不用担心越界
    _scrollController.nextItem(
      duration: const Duration(milliseconds: 80), 
      curve: Curves.linear
    );
  });
}

// 别忘了在组件销毁时释放资源
@override
void dispose() {
  _scrollController.dispose();
  _autoScrollTimer?.cancel();
  super.dispose();
}

实现效果示例

效果示例图

补充说明

  • 调整_scrollDuration参数可以修改自动滚动的总时长
  • 调整_scrollInterval和nextItem的duration参数可以控制滚动速度,数值越小滚动越快
  • 滚动结束后可以根据业务需求自定义最终停留的item位置

内容的提问来源于stack exchange,提问作者Md. Sabik Alam Rahat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:30:01