当前initialDate设置为DateTime.now((最初必须显示今天的日期,但当我选择任何日期并再次打开日期选择器时,初始日期应该是我之前选择的日期。如何做到这一点:
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");
}
});
您需要将该值保存在某个位置。。。
DateTime? selectedDateTime;
...
child: TextField( onTap: () async {
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: selectedDateTime ?? DateTime.now(),
...).then(pickedDate) { setState(() => selectedDateTime = pickedDate);}