Home > other >  I wants to show selected date in date picker when I tap again on date picker using flutter
I wants to show selected date in date picker when I tap again on date picker using flutter

Time:10-11

Currently initialDate is set to DateTime.now() initially today's date must shown but when I select any date and again opens the Date Picker initial date should be the one which I have selected previously. How to do this:

 child: TextField(
            onTap: () async {
              DateTime? pickedDate = await showDatePicker(
                context: context,

                initialDate: DateTime.now(),
                firstDate: DateTime(
                    1991), //DateTime.now() - not to allow to choose before today.
                lastDate: DateTime(2025),
                // onConfirm:widget.onChanged,
              ).then((pickedDate) {
                if (pickedDate != null) {
                  // print(
                  //     pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                  String formattedDate =
                      DateFormat('yyyy-MM-dd').format(pickedDate);

                  print(formattedDate);

                  setState(() {
                    startDtcontroller.text = formattedDate;

                    //set output date to TextField value.
                  });
                  //print(startDtcontroller.text);
                  //formatted date output using intl package =>  2021-03-16
                  //you can implement different kind of Date Format here according to your requirement
                  // DateFormat df = new DateFormat("yyyy-MM-dd");
                  // String stDate = df.format(pickedDate);
                  // print(stDate);

                  widget.onChanged(formattedDate);
                } else {
                  print("Date is not selected");
                }
              });

CodePudding user response:

You need to save that value somewhere...

DateTime? selectedDateTime;

...

child: TextField(  onTap: () async {
              DateTime? pickedDate = await showDatePicker(
                context: context,

                initialDate: selectedDateTime ?? DateTime.now(),
...).then(pickedDate) { setState(() => selectedDateTime = pickedDate);}
  • Related