Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 610
Amanda Wong Avatar asked Aug 04 '18 07:08

Amanda Wong


2 Answers

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,
like image 62
Shady Aziza Avatar answered Oct 22 '22 17:10

Shady Aziza


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,
like image 22
Moti Bartov Avatar answered Oct 22 '22 16:10

Moti Bartov