如何在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), )
关键说明
- 提前初始化
selectedDayStart为非null值,避免空指针异常; - 在弹出选择器前通过
setState更新selectedDayStart的时分,确保显示文本与选择器初始时间同步; - 如果
_initialTime是动态变化的(比如基于上次选择的时间),只需保证在弹出前将其时分同步到selectedDayStart即可。
内容的提问来源于stack exchange,提问作者Ata Berk Çinetçi
相关产品推荐
相关产品推荐

