Reputation: 463
i am coding an application for events and I disabled all days except Sats in my case
and it works perfect but I am getting a problem how to set initial date for the first Sat after today if it's not Sat or today if it's Sat as default value in dataPicker
also how I can disable all Days before today even Sats.
here is my code
DateTime _dateTime=DateTime.now();
showDatePicker(
context: context,
initialDate:_dateTime.weekday == 1||_dateTime.weekday == 2||_dateTime.weekday == 3||_dateTime.weekday == 4||_dateTime.weekday == 5 ? DateTime(DateTime.now().year, DateTime.now().month, 1) : _dateTime,
firstDate: DateTime(2019),
lastDate: DateTime(2020),
selectableDayPredicate: (val)=> val.weekday == 1 ||val.weekday == 2 ||val.weekday == 3 ||val.weekday == 4 || val.weekday == 5 ? false : true,
);
this code works perfect but it make default date time is the first day of year as default date if today is not Sat. could you please help in this issue ?
Upvotes: 1
Views: 2872
Reputation: 3147
As I conclude from your question, here are your requirements :
how to :
disabled all days except Sats
also how I can disable all Days before today even Sats
set initial date for the first Sat after today if it's not Sat
or today if it's Sat as default value in dataPicker
bool defineSelectable(DateTime val) {
DateTime now = DateTime.now();
// disabled all days before today
if (val.isBefore(now)) {
return false;
}
// disabled all days except Sats
switch (val.weekday) {
case saturday:
return true;
break;
default:
return false;
}
}
void handleButton(context) async {
DateTime chosenDate = await showDatePicker(
...
selectableDayPredicate: defineSelectable,
);
}
int daysToAdd(int todayIndex, int targetIndex) {
if (todayIndex < targetIndex) { // jump to target day in same week
return targetIndex - todayIndex;
} else if (todayIndex > targetIndex) { // must jump to next week
return 7 + targetIndex - todayIndex;
} else {
return 0; // date is matched
}
}
DateTime defineInitialDate() {
DateTime now = DateTime.now();
int dayOffset = daysToAdd(now.weekday, saturday);
return now.add(Duration(days: dayOffset));
}
void handleButton(context) async {
DateTime chosenDate = await showDatePicker(
...
initialDate: defineInitialDate(),
...
);
}
You may look into this repo and build it locally TimePickerScreen
Upvotes: 3