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

如何关联DateTime与Reservations列表并在ListView中展示

实现按时段展示预约信息的Flutter代码

需求说明

现有两类数据集合:

  • 第一类为DateTime类型的时间集合,按每30分钟一个时段,从当日8:00开始生成29个时段
  • 第二类为Reservation类型的预约集合,需将预约信息匹配到对应时段中,无预约的时段显示空白区域

核心视图构建代码

通过Consumer监听预约列表数据变化,筛选出当日的预约记录,再遍历生成每个时段的列表项:

Consumer<List<Reservation>>(
  builder: (context, snapshot, _) {
    // 筛选出与选中日期同一天的预约
    var reservedTimes = snapshot.where((element) => 
        isSameDay(element.dateTimeStart, _selectedDay));
    // 设定当日时段的起始时间:8:00
    final startTime = DateTime(_selectedDay.year,
        _selectedDay.month, _selectedDay.day, 8, 0);

    return ListView.builder(
        itemCount: 29, // 生成从8:00到22:00的29个30分钟时段
        itemBuilder: (context, index) {
          // 计算当前遍历到的时段时间
          final time = startTime.add(Duration(minutes: 30 * index));

          // 查找当前时段对应的预约记录
          final matchingReservation = reservedTimes.firstWhereOrNull(
              (element) => isReservationTime(time, element));

          // 自定义列表项,传入时段时间和匹配到的预约
          return customListTile(time, matchingReservation);
        });
  },
),

时段与预约匹配校验方法

用于判断当前时间是否处于某个预约的时间段内:

bool isReservationTime(DateTime time, Reservation reservation) {
  return (time.isAtSameMomentAs(reservation.dateTimeStart) ||
          time.isAfter(reservation.dateTimeStart)) &&
      time.isBefore(reservation.dateTimeEnd);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:17:24