How do I use the SelectableDayPredicate to limit my DatePicker to only weekdays?
Asked Answered
C

3

10

I have implemented a DatePicker to my Flutter application. I am trying to limit the picker to only allow the users to choose weekdays. However, I am not sure how to do this. I believe it has got to do with the SelectableDayPredicate. Below is a snippet of my code:

Future<Null> _selectDate(BuildContext context) async {
  final DateTime picked = await showDatePicker(
    context: context,
    initialDate: _date,
    firstDate: new DateTime(DateTime.now().year),
    lastDate: new DateTime(DateTime.now().year+1),
    // to do: I am pretty sure the SelectableDayPredicate should go somewhere here.
  );

  if (picked != null && picked != _date) {
    setState(() {
      _date = picked;
    });
  }
}

The _selectDate function is called when the user taps on the listTile.

Cyperaceous answered 4/8, 2018 at 7:55 Comment(0)
C
22

Here is an example where I omit Fridays and Saturdays from the picker, you can follow the logic here to achieve what you want:

selectableDayPredicate: (DateTime val) =>
            val.weekday == 5 || val.weekday == 6 ? false : true,
Countryside answered 4/8, 2018 at 11:25 Comment(2)
When I click on the date that on weekend that added into controller selectedDates first time after that disable date how I can achieve that first time click not able to selected?Shipwreck
This selectableDayPredicate is not available in the DateRangePicker. What can be the possible solution for it, so that I can enable or disable past or future dates? Please help me.Dowski
P
4

Thanks!

However, for date picker you must provide an initialValue which probably should be 'today', but if 'today' is a weekend, then you will get exception!

So iv'e set the initial to 1'st day of month on this case

    initialDate: _dateTime.weekday == 5 || _dateTime.weekday == 6 ? DateTime(DateTime.now().year, DateTime.now().month, 1) :  _dateTime ,
    selectableDayPredicate: (DateTime val) =>
    val.weekday == 5 || val.weekday == 6 ? false : true,
Polycythemia answered 3/8, 2019 at 9:14 Comment(0)
T
0

I got the reference from different answers and handled the date selection of weekdays only, using the following code:

extension DateTimeExtension on DateTime {
  DateTime next(int day) {
    return this.add(
        Duration(days: (day - this.weekday) % DateTime.daysPerWeek,),
    );
  }
}

After this, set the 'initialDate' and 'selectableDayPredicate' as per below:

initialDate: ((DateTime.now().weekday == DateTime.saturday) || (DateTime.now().weekday == DateTime.sunday)) ? DateTime.now().next(DateTime.monday) : DateTime.now(),

selectableDayPredicate: (DateTime val) => val.weekday == DateTime.saturday || val.weekday == DateTime.sunday ? false : true,

My Reference:

  1. As per @Moti_Bartov
  2. As per @davideliseo
Tapster answered 4/1, 2024 at 5:31 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.