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

如何在Flutter CupertinoDatePicker中设置初始显示时间?

解决CupertinoDatePicker弹出时同步初始时间的问题

当前代码的问题在于,只有滑动选择器触发onDateTimeChanged回调时,才会更新selectedDayStart的值。但弹出选择器时,选择器显示的是_initialTime,而selectedDayStart仍保持原有值(或为null),导致显示的时间与选择器初始状态不一致。

解决方法

在弹出选择器的按钮点击事件中,先同步_initialTime的时分到selectedDayStart(保留原有的年月日),再弹出选择器。这样选择器刚弹出时,显示文本就会和选择器的初始时间一致。

修改后的完整代码示例

变量定义(补充初始化,避免空指针)

DateTime selectedDayStart = DateTime.now(); // 初始化默认日期为当天
DateTime _initialTime = DateTime(
  selectedDayStart.year,
  selectedDayStart.month,
  selectedDayStart.day,
  9, 0 // 设置初始时间为当天9:00
);

弹出选择器的按钮逻辑

ElevatedButton(
  onPressed: () {
    // 弹出前先同步初始时间到selectedDayStart
    setState(() {
      selectedDayStart = DateTime(
        selectedDayStart.year,
        selectedDayStart.month,
        selectedDayStart.day,
        _initialTime.hour,
        _initialTime.minute,
      );
    });
    // 弹出Cupertino选择器弹窗
    showCupertinoModalPopup(
      context: context,
      builder: (context) => Container(
        height: 220,
        color: CupertinoColors.white,
        child: CupertinoDatePicker(
          mode: CupertinoDatePickerMode.time,
          minuteInterval: 15,
          initialDateTime: _initialTime,
          use24hFormat: true,
          onDateTimeChanged: (time) {
            setState(() {
              selectedDayStart = DateTime(
                selectedDayStart.year,
                selectedDayStart.month,
                selectedDayStart.day,
                time.hour,
                time.minute,
              );
            });
          },
        ),
      ),
    );
  },
  child: const Text("选择开始时间"),
)

时间显示组件

Text(
  "Başlangıç Saati ${DateFormat("HH:mm").format(selectedDayStart)}",
  style: const TextStyle(fontSize: 20),
)

关键说明

  1. 提前初始化selectedDayStart为非null值,避免空指针异常;
  2. 在弹出选择器前通过setState更新selectedDayStart的时分,确保显示文本与选择器初始时间同步;
  3. 如果_initialTime是动态变化的(比如基于上次选择的时间),只需保证在弹出前将其时分同步到selectedDayStart即可。

内容的提问来源于stack exchange,提问作者Ata Berk Çinetçi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:12:59