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

Flutter CupertinoDatePicker如何保留00:00并禁用00:15-09:00?

实现CupertinoDatePicker保留00:00并禁用00:15-09:00时间段

由于CupertinoDatePicker本身仅支持设置连续的时间范围,无法直接跳过中间特定区间,我们可以通过初始化校验+选择事件拦截的方式实现需求,具体步骤如下:

1. 初始化时修正非法初始值

先判断传入的currentHour和currentMinute是否落在禁用区间,如果是则默认将初始时间设为00:00:

DateTime currentDate = () {
  DateTime initial = DateTime(1900, 1, 1, currentHour, currentMinute);
  // 判断是否处于00:15到09:00的禁用区间
  bool isInDisabledRange = (initial.hour == 0 && initial.minute >= 15) || 
                           (initial.hour > 0 && initial.hour < 9);
  return isInDisabledRange ? DateTime(1900, 1, 1, 0, 0) : initial;
}();

2. 修改Picker配置并拦截非法选择

将minimumDate设为00:00保证该时间可选,然后在onDateTimeChanged中校验选中时间,若落在禁用区间则拒绝更新或强制切换到合法时间:

CupertinoDatePicker(
  use24hFormat: true,
  mode: CupertinoDatePickerMode.time,
  minuteInterval: 15,
  initialDateTime: currentDate,
  // 最小时间设为00:00,确保该时间可选
  minimumDate: DateTime(currentDate.year, currentDate.month, currentDate.day, 0, 0),
  // 最大时间保留原有配置
  maximumDate: DateTime(currentDate.year, currentDate.month, currentDate.day + nextDay, maxHours, maxMinutes),
  onDateTimeChanged: (DateTime newDateTime) {
    // 校验选中时间是否在禁用区间
    bool isDisabled = (newDateTime.hour == 0 && newDateTime.minute >= 15) || 
                      (newDateTime.hour > 0 && newDateTime.hour < 9);
    if (!isDisabled) {
      currentDate = newDateTime;
      setState(() {}); // StatefulWidget中需调用setState更新UI
    } else {
      // 选中禁用时间时,强制切换回00:00(也可根据需求改为09:00)
      currentDate = DateTime(currentDate.year, currentDate.month, currentDate.day, 0, 0);
      setState(() {});
    }
  },
)

说明

  • 这种方式是低成本的折中方案:用户仍能滚动到禁用区间,但选择后会自动切回合法时间;
  • 如果需要完全禁止用户滚动到禁用区间,需要自定义Picker组件,成本较高,上述方案更适合大多数场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:05:07