Category / Section
How to add active dates in the Flutter Date Range Picker (SfDateRangePicker)
2 mins read
In the Flutter date range picker, you can add active dates by using the reverse of the blackoutDates concept.
STEP 1: Set up default values in initState() for the date range picker.
List<DateTime> _blackoutDateCollection = <DateTime>[];
late List<DateTime> _activeDates;
@override
void initState() {
DateTime today = DateTime.now();
today = DateTime(today.year, today.month, today.day);
_activeDates = [
today,
today.add(Duration(days: 5)),
today.add(Duration(days: 10)),
today.add(Duration(days: 15)),
today.add(Duration(days: 20)),
today.add(Duration(days: 25)),
today.add(Duration(days: 30)),
today.add(Duration(days: 35))
];
super.initState();
}
STEP 2: Use the onViewChanged callback, check the mentioned active dates are equal to the visible dates. If it is equal, then allow those dates are active and can be selected. Otherwise, add remaining dates in the blackout dates collection.
void viewChanged(DateRangePickerViewChangedArgs args) {
DateTime date;
DateTime startDate = args.visibleDateRange.startDate!;
DateTime endDate = args.visibleDateRange.endDate!;
List<DateTime> _blackDates = <DateTime>[];
for (date = startDate;
date.isBefore(endDate) || date == endDate;
date = date.add(const Duration(days: 1))) {
if (_activeDates.contains(date)) {
continue;
}
_blackDates.add(date);
}
SchedulerBinding.instance!.addPostFrameCallback((timeStamp) {
setState(() {
_blackoutDateCollection = _blackDates;
});
});
}
STEP 3: Assign the above date collections to the blackoutDates property of the SfDateRangePicker.
child: SfDateRangePicker(
view: DateRangePickerView.month,
selectionMode: DateRangePickerSelectionMode.single,
monthViewSettings: DateRangePickerMonthViewSettings(
blackoutDates: _blackoutDateCollection,
),
monthCellStyle: DateRangePickerMonthCellStyle(
blackoutDateTextStyle: TextStyle(
color: Colors.grey, decoration: TextDecoration.lineThrough),
),
onViewChanged: viewChanged,
showNavigationArrow: true,
),
|
|
Didn't find an answer?
Contact Support