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

Flutter如何在HorizontalPicker中展示JSON时间及横向时间轴实现方案

报错原因

你使用的HorizontalPicker组件要求minValue、maxValue参数为double类型,但你的JSON中time字段是12:00PM格式的字符串,无法直接通过double.parse转换为数值,所以触发了格式异常。同时你的代码存在数组越界风险:data.schedule.delivery[data.schedule.delivery.length]的下标超出了数组范围,合法最大下标为data.schedule.delivery.length-1。

修复方案

  1. 先将时间字符串转换为可计算的数值类型:比如把12:00PM转成12.0、2:30PM转成14.5,再传给minValue和maxValue参数,在onChanged回调中再把选中的数值转回h:mma格式的字符串展示即可。
  2. 修正maxValue的数组下标,避免越界崩溃。

其他横向时间选择器实现方案

  • 自定义实现(最适配需求):直接用横向ListView自行实现,自由度最高,完全可以匹配你要的UI效果,参考代码如下:
// 先引入intl包处理时间格式化
import 'package:intl/intl.dart';

// 预先处理JSON中的时间数据为DateTime列表
List<DateTime> deliveryTimeList = data.schedule.delivery.map((item) {
  return DateFormat.jm().parse(item.time.toString());
}).toList();
int selectedTimeIndex = 0;

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Container(
      margin: EdgeInsets.zero,
      width: double.infinity,
      height: 120,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: deliveryTimeList.length,
        physics: const BouncingScrollPhysics(),
        itemBuilder: (context, index) {
          final isSelected = index == selectedTimeIndex;
          return GestureDetector(
            onTap: () => setState(() => selectedTimeIndex = index),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              alignment: Alignment.center,
              child: Text(
                DateFormat.jm().format(deliveryTimeList[index]),
                style: TextStyle(
                  color: isSelected ? Colors.black : Colors.grey,
                  fontSize: isSelected ? 22 : 16,
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                ),
              ),
            ),
          );
        },
      ),
    ),
  );
}

如果需要滚动自动居中高亮,可以加ScrollController监听滚动位置,计算当前居中位置对应的下标自动更新选中状态即可。

  • 第三方库实现:可以用timeline_tile、flutter_swiper这类成熟的第三方组件快速实现横向滚动选择效果,省去自行处理滚动监听的逻辑。
  • 单选项滚动实现:如果需要每次滚动只切换一个时间选项,用PageView配合PageController实现即可,滑动手感更顺滑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:15:00