late DateTime datePicked = DateTime.now();
void showDatePickerForUser() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime.now().add(const Duration(days: 365)),
).then((value) {
setState(() {
datePicked = value!;
});
});
}
Container(
height: MediaQuery.of(context).size.height * 0.08,
width: MediaQuery.of(context).size.width * 0.9,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colours().borderColor,
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.only(left: 20),
child: Text(
datePicked.toString().substring(0, 10),
style: GoogleFonts.ubuntu(
fontSize: 18,
//fontWeight: FontWeight.bold,
color: Colours().unSelectedText,
),
),
),
Padding(
padding: const EdgeInsets.only(right: 10),
child: IconButton(
onPressed: () {
showDatePickerForUser();
},
icon: const Icon(
Icons.calendar_month_outlined,
color: Colors.black,
size: 28,
),
),
),
],
),
)
The date user picks does not being picked and shown on the field.
3
Answers
Maybe it’s helpful for you!
Here is a complete code to run with the given changes:
Changes made:
1-Used datePicked as the initial date for the showDatePicker.
2-Checked if the picked date is not null before updating the state.
3-Formatted the displayed date using toLocal() to show it in the local time.
4-Used ${datePicked.toLocal()} to get the date part only.
Make sure your class extends a StateFulWidget.
I checked your code and it works fine.