I'm beginning to learn flutter and I'm working with showDatePicker
There, I can manually assign the current year to firstDate
firstDate: DateTime(2021)
I'm trying to automatically use the current year as firstDate.
For that, what I did so far was:
void _showDatePicker() {
var currentYear = DateFormat.y().format(DateTime.now()) as DateTime;
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: currentYear,
lastDate: DateTime.now()
);
}
If I remove as DateTime I get the error in firstDate: currentYear:
The argument type 'String' can't be assigned to the parameter type 'DateTime'
and if I add as DateTime, I get the error:
type 'String' is not a subtype of type 'DateTime' in type cast
How can I fix it?
A simpler and more performant solution would be to not use strings at all. They're unnecessary and add additional overhead.
You can get the current year from the DateTime object. And pass it to the default DateTime constructor. No string conversion, no intl package, no performance hit from parsing a date from a string.
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(DateTime.now().year),
lastDate: DateTime.now()
);
Hey Please try below code.
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2025),
)
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime.now()
);
I have made some changes in your code this code will work for you.
Your current year is string so i have converted it to int then pass inside DateTime()
void _showDatePicker() {
int currentYear = int.parse(DateFormat.y().format(DateTime.now()));
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(currentYear),
lastDate: DateTime.now());
}
Related
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");
}
});
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);}
Blockquote
how to set once a user select a date in one field can't able to pick less than in another field in flutter
Use this gor the first date picker
DateTime? startDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime(2100),
);
Use this for the next datepicker
DateTime? endPickedDate = await showDatePicker(
context: context,
initialDate: startDate,
firstDate: startDate,
lastDate: DateTime(2100),
);
If you notice you can see the initial date of end date picker is the picked value from startDatePicker.
Also a best approach will be to use a date range picker
I have this code to display DatePicker and after which TimePicker will come up and I will retrive all the seleted values and it was working perfectly fine until I migrated to null safety by creating a flutter project and coping all my code to the new project and also and doing a few "pub get, Upgrade"
Below is my code:
//Select Date and Time Widget
Future _selectDayAndTimeL(BuildContext context) async {
DateTime _selectedDay = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2021),
lastDate: DateTime(2030),
builder: (BuildContext context, Widget child) => child);
TimeOfDay _selectedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (_selectedDay != null && _selectedTime != null) {
//a little check
}
setState(() {
selectedDateAndTime = DateTime(
_selectedDay.year,
_selectedDay.month,
_selectedDay.day,
_selectedTime.hour,
_selectedTime.minute,
);
// _selectedDate = _selectedDay;
});
// print('...');
}
Now I got this error:
A value of type 'DateTime?' can't be assigned to a variable of type
'DateTime'.
A value of type 'TimeOfDay?' can't be assigned to a variable of type
'TimeOfDay'.
Check the image to see... I have gone through the questions I saw on almost same issue but it did not solve my problem
How do i solve this error
showDatePicker returns Future DateTime?:
Future<DateTime?> showDatePicker(...)
So, you need to change the following:
DateTime _selectedDay = await showDatePicker(...)
to:
DateTime? _selectedDay = await showDatePicker(...)
showTimePicker returns Future TimeOfDay?:
Future<TimeOfDay?> showTimePicker(...)
So, change the following:
TimeOfDay _selectedTime = await showTimePicker(...);
to:
TimeOfDay? _selectedTime = await showTimePicker(...);
Either null safe variable like TimeOfDay?, or you can get the value at risk with (await showTimePicker(...))!
Check more for null safety of dart
I am trying to give user an option to select date between 7 days.
Like today is 2nd March then user can select any date before 10th March.
My current code is showing first date as 01/01/03 i am not sure why it is giving me this date.
Here is the code.
_pickedDate() async {
rescheduleddate = await showDatePicker(
context: context,
firstDate: DateTime(DateTime.now().day + 1),
lastDate: DateTime(DateTime.now().day + 7),
initialDate: DateTime(DateTime.now().day + 1),
);
if (rescheduleddate != null) {
setState(() {
pickeddate = rescheduleddate;
});
}
}
I am not sure what am i doing wrong because if i add year instead of day then it is working fine.
I managed to solve this one.
_pickedDate() async {
rescheduleddate = await showDatePicker(
context: context,
firstDate: DateTime.now().add(new Duration(days: 1)),
lastDate: DateTime.now().add(new Duration(days: 7)),
initialDate: DateTime.now().add(new Duration(days: 1)),
);
if (rescheduleddate != null) {
setState(() {
pickeddate = rescheduleddate;
});
}
}
I think the issue might be that you aren't properly adding a duration to the current DateTime object. By calling .day you are just getting the number of the day as an integer, which you're then trying to plug back into a new DatePicker as an argument. For example, if today is March 2nd, DateTime.now().day would return 2, so your firstDate value is currently trying to evaluate what DateTime(3) is (if you inspect the DateTime function, the first argument is the year as an integer, so it's setting the date to 01/01/03). Try doing this:
rescheduleddate = await showDatePicker(
context: context,
firstDate: DateTime.now().add(Duration(days: 1)),
lastDate: DateTime.now().add(Duration(days: 7)),
initialDate: DateTime.now().add(Duration(days: 1)),
);
How would I format the date returned to be displayed with the day and month eg 23 AUG with my code.
var finaldate;
void callDatePicker() async {
var order = await getDate();
setState(() {
finaldate = order;
});
}
Future<DateTime> getDate() {
return showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2020),
lastDate: DateTime(2025),
Text('$finaldate',
You can use DateFormat from the intl package
DateFormat('dd MMM, yyyy').format(finaldate) // gives 27 Jun, 2020