How to select a week(custom) in the Flutter Date Range Picker (SfDateRangePicker)

1.4k views Asked by At

I try to implement a weekly selector by following this example - https://www.syncfusion.com/kb/11412/how-to-select-a-week-in-the-flutter-date-range-picker-sfdaterangepicker

The problem I encounter is that the "args.value" from DateRangePickerSelectionChangedArgs returns a date range from Sunday to Saturday. What I want is for the DateRangePickerSelectionChangedArgs to return a date range from Monday to Sunday. I want the weekly selector to select the whole week from Monday to Sunday not from Sunday to Saturday as shown in this screenshot.

enter image description here

I try the codes below. I tried adding one to the start date and to the end date so that Sunday becomes Monday and Saturday becomes Sunday, but the code didn't work when I did that.

  void selectionChanged(DateRangePickerSelectionChangedArgs args) {
      isSameDate(date1, date2) {
        if (date2 == date1) {
          return true;
        }
        if (date1 == null || date2 == null) {
          return false;
        }
        return date1.month == date2.month && date1.year == date2.year && date1.day == date2.day;
      }

      int firstDayOfWeek = DateTime.sunday % 7;
      int endDayOfWeek = (firstDayOfWeek - 1) % 7;
      endDayOfWeek = endDayOfWeek < 0 ? 7 + endDayOfWeek : endDayOfWeek;
      PickerDateRange ranges = args.value;

      DateTime date1 = ranges.startDate!;
      DateTime date2 = (ranges.endDate ?? ranges.startDate)!;

      if (date1.isAfter(date2)) {
        var date = date1;
        date1 = date2;
        date2 = date;
      }
      int day1 = date1.weekday % 7;
      int day2 = date2.weekday % 7;

      DateTime dat1 = date1.add(Duration(days: (firstDayOfWeek - day1) + 1));
      DateTime dat2 = date2.add(Duration(days: (endDayOfWeek - day2) + 1));

      if (!isSameDate(dat1, date1) || !isSameDate(dat2, date2)) {
        datePickerController.selectedRange = PickerDateRange(dat1, dat2);
      }
  }
1

There are 1 answers

0
Kumar On

You can customize the first day of the week in the date range picker by using the FirstDayofWeek property from the MonthViewSettings. Refer to the UG documentation to know more about FirstDayofWeek,

https://help.syncfusion.com/flutter/daterangepicker/getting-started#change-first-day-of-week

Refer to the code snippets to achieve your requirement, CustomWeek

customweekincalendar