Flutter CupertinoDatePicker时间模式24小时格式:在00:00和09:00之间禁用范围?

bvjxkvbb  于 2023-03-31  发布在  Flutter
关注(0)|答案(1)|浏览(229)

我有这个CupertinoDatePicker设置在时间模式与24小时格式和15分钟的间隔:

CupertinoDatePicker(
                      use24hFormat: true,
                      mode: CupertinoDatePickerMode.time,
                      minuteInterval: 15,
                      initialDateTime: currentDate,
                      minimumDate: DateTime(currentDate.year, currentDate.month,
                          currentDate.day, minHours, minMinutes),
                      maximumDate: DateTime(currentDate.year, currentDate.month,
                          currentDate.day + nextDay, maxHours, maxMinutes),
                      onDateTimeChanged: (DateTime newDateTime) {
                        currentDate = newDateTime;
                      }
                     )

我将初始日期设置为currentDate,其定义如下:

DateTime currentDate =
        DateTime(1900, 1, 1, currentHour, currentMinute);

其中currentHour和currentMinute是我在这个函数中传递的两个变量。在显示DatePicker之前的函数中,我还计算了minHours,minMinutes和maxHours和maxMinutes,这应该限制用户可以选择小时和分钟的范围,通过设置Picker的minimumDate和maximumDate来完成。
唯一的大问题是,我想计数午夜(所以00:00)作为最大时间在某些情况下。所以,例如,如果我想禁用00:15和9:00之间,但保持00:00启用?

wfauudbj

wfauudbj1#

要实现您的想法,您需要自定义CupertinoPicker并过滤不需要的值:

class GianLuca extends StatefulWidget {
  const GianLuca({Key key}) : super(key: key);

  @override
  State<GianLuca> createState() => _GianLucaState();
}

class _GianLucaState extends State<GianLuca> {
  @override
  Widget build(BuildContext context) {
    List<DateTime> timeSlots = _generateTimeSlots(DateTime(1900, 1, 1, 0, 0), DateTime(1900, 1, 2), 15);
    return  MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child:   CupertinoPicker(
            scrollController: FixedExtentScrollController(initialItem: 0),
            itemExtent: 32.0,
            onSelectedItemChanged: (int index) {
              // Handle selected time
            },
            children: timeSlots.map((time) {
              return Text(
                DateFormat.Hm().format(time),
                style: const TextStyle(fontSize: 20.0),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }

  List<DateTime> _generateTimeSlots(DateTime startDate, DateTime endDate, int minuteInterval) {
    final List<DateTime> timeSlots = [];
    DateTime currentDate = startDate;

    while (currentDate.isBefore(endDate)) {
      if (currentDate.hour >= 9 || (currentDate.hour == 0 && currentDate.minute == 0)) {
        timeSlots.add(currentDate);
      }
      currentDate = currentDate.add(Duration(minutes: minuteInterval));
    }

    return timeSlots;
  }

}

快乐编码...

相关问题