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

Flutter Swiper实现预约日历滑块时重复显示日期问题求助

问题排查与修复方案

核心问题分析

  • 日期固定显示:代码中Text(values[1])硬编码了索引值1,导致无论滑动到哪个滑块,始终显示values列表的第二个元素(Tuesday),没有根据当前滑块的索引动态获取对应日期。
  • 索引不更新:局部变量_index的修改无法触发组件重建,所以滑动后索引始终显示初始值0,无需额外维护这个变量,直接使用itemBuilder传入的index参数即可。
  • 条目数量不匹配:itemCount设置为10,但你的日期数据只有5条,会导致后续滑块索引越界,应该将itemCount与数据源长度保持一致。

修复后的代码

Swiper imageSlider(context) {
  var weekDays = {'19':'Monday','20':'Tuesday','21':'Wednesday','22':'Thursday','23':'Friday'};
  List keys = weekDays.keys.toList();
  List values = weekDays.values.toList();

  return Swiper(
    viewportFraction: 0.2,
    autoplay: false,
    itemBuilder: (BuildContext context, int index) {
      return Container(
        child: Column(
          children: [
            Container(
              height: 30,
              color: Colors.blue,
            ),
            Text('${keys[index]}'), // 显示对应日期数字
            Text(values[index]) // 显示对应星期
          ],
        ),
      );
    }, 
    itemCount: weekDays.length); // 条目数与数据源一致
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:50:24