How can I set the initial time for the time picker in Flutter CupertinoDatePicker?

1k Views Asked by At

In my CupertinoDatePickerMode.time , I need to slide the picker for setting the time which is currently on the picker with onDateTimeChanged. I click the button and the picker pops up. I can set the time like I said only after sliding the picker.

So my question is: How can I set the time when just the picker pops up.

This is my variable:

DateTime? selectedDayStart;

This is my picker:

return 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);
      });
    },
  );

This is how I show the time:

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

There are 2 best solutions below

0
On

You can set Time on initialDateTime.

DateTime _initialTime = DateTime.now().copyWith(
  hour: 11,
  minute: 40,
);
CupertinoDatePicker(
  mode: CupertinoDatePickerMode.time,
  minuteInterval: 10,
  initialDateTime: _initialTime,

minuteInterval should be _initialTime.minute%minuteInterval==0. Make sure to fill this(%==0) condition.

0
On

I solved it with using CupertinoDatePicker in Stateful Widget and called initState

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

  @override
  _MyCupertinoDatePickerState createState() => _MyCupertinoDatePickerState();
}

class _MyCupertinoDatePickerState extends State<MyCupertinoDatePicker> {
  @override
  void initState() {
    super.initState();
    // set the initial date to the current date and time
    selectedDate = DateTime.now();
    print(selectedDate);
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoDatePicker(
      mode: CupertinoDatePickerMode.time,
      initialDateTime: selectedDate,
      onDateTimeChanged: (DateTime newDateTime) {
        setState(() {
          selectedDate = newDateTime;
          print(selectedDate);
          
        });
      },
    );
  }
}