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

Flutter Web中flutter_timetable组件鼠标及键盘箭头横向滚动方案咨询

Flutter Web中flutter_timetable横向滚动实现思路

思路一:利用组件自带控制器实现精准滚动

flutter_timetable的TimetableController是核心控制类,可直接通过它调整可视时间范围来实现横向滚动:

  • 初始化TimetableController,指定初始可视时间范围
  • 用Listener包裹组件,监听Web端的PointerScrollEvent,根据滚动偏移量(event.scrollDelta.dx或把纵向滚轮转为横向)调整可视范围
  • 配合animateTo或直接更新visibleRange实现平滑滚动

示例代码:

final timetableController = TimetableController(
  initialVisibleRange: DateTimeRange(
    start: DateTime.now().subtract(const Duration(hours: 4)),
    end: DateTime.now().add(const Duration(hours: 4)),
  ),
);

Listener(
  onPointerScroll: (event) {
    // 处理鼠标横向滚动,或把纵向滚轮转为横向偏移
    final scrollStep = const Duration(minutes: 30);
    final offset = event.scrollDelta.dx != 0 
        ? event.scrollDelta.dx 
        : -event.scrollDelta.y; // 纵向滚轮转横向

    if (offset != 0) {
      final currentRange = timetableController.visibleRange;
      final direction = offset > 0 ? -1 : 1;
      timetableController.animateTo(
        DateTimeRange(
          start: currentRange.start.add(scrollStep * direction),
          end: currentRange.end.add(scrollStep * direction),
        ),
        duration: const Duration(milliseconds: 120),
      );
    }
  },
  child: Timetable(
    controller: timetableController,
    // 你的课程数据、样式配置等
  ),
);

思路二:外部包裹横向滚动组件兜底

如果组件自带控制器不好用,可将flutter_timetable放在SingleChildScrollView中,借助通用滚动组件实现横向滚动:

  • 配置SingleChildScrollView为横向滚动,绑定ScrollController
  • 用RawKeyboardListener监听左右箭头键,调用控制器的jumpTo或animateTo调整偏移
  • 注意给timetable设置足够宽的父容器,确保滚动空间

示例代码:

final scrollController = ScrollController();
final focusNode = FocusNode();

RawKeyboardListener(
  focusNode: focusNode,
  onKey: (event) {
    if (event.isKeyPressed(LogicalKeyboardKey.arrowLeft)) {
      scrollController.jumpTo(scrollController.offset - 60);
    } else if (event.isKeyPressed(LogicalKeyboardKey.arrowRight)) {
      scrollController.jumpTo(scrollController.offset + 60);
    }
  },
  child: SingleChildScrollView(
    scrollDirection: Axis.horizontal,
    controller: scrollController,
    child: SizedBox(
      width: 3000, // 根据实际时间范围设置宽度
      child: Timetable(
        // 组件配置
      ),
    ),
  ),
);

关键注意事项

  • 键盘事件监听需要组件获得焦点,所以RawKeyboardListener的focusNode需确保处于激活状态(可在组件初始化时调用focusNode.requestFocus())
  • 部分浏览器默认鼠标横向滚动需按住Shift键,可通过Listener将纵向滚轮事件转为横向偏移,提升用户体验
  • 若组件内部自带滚动逻辑,需检查是否存在冲突,可尝试禁用内部滚动(查看组件文档是否有相关配置)

内容的提问来源于stack exchange,提问作者Lisofo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:07:29