skip to Main Content

I have a section in my Flutter app where a user can click on a date and it will retirever from the database all entries from that date, The problem is if i go into the calendar and click a date say from two months ago, when i open the calendar again it will have today highlighted instead of the date i picked previously meaning i have to scroll all the way back to my desired date, How do I fix this

THe code:

      child: TextFormField(
        controller: _date,
        decoration: const InputDecoration(
            icon: Icon(Icons.calendar_today_rounded),
            labelText: "Select Date"),
        onTap: () async {
          DateTime? pickeddate = await showDatePicker(
              context: context,
              initialDate: DateTime.now(),
              firstDate: DateTime(2000),
              lastDate: DateTime(2101));

          if (pickeddate != null) {
            setState(() {
              _date.text = DateFormat('yyyy-MM-dd').format(pickeddate);
              currentDateSelected = _date.text;
              // updateDate(DateFormat('yyyy-MM-dd').format(pickeddate));
              _refreshSets();
              //print(DateFormat('yyyy-MM-dd').format(pickeddate));
            });
          }

          //Here i need to send off to the database that pickeddate
        },
      ),

2

Answers


  1. Read the showDatePicker constructor in the doc

    Future<DateTime?> showDatePicker(
    {required BuildContext context,
    required DateTime initialDate,
    required DateTime firstDate,
    required DateTime lastDate,
    DateTime? currentDate,
    ...
    

    The currentDate represents the current day (i.e. today). This date will be highlighted in the day grid. If null, the date of DateTime.now() will be used. That causes your problem.

    Login or Signup to reply.
  2. You have a property by the name initialDate which is used to set the initial value of the date picker.

    DateTime selectedDate = DateTime.now();
    ...
     onTap: () async {
         DateTime? pickedDate = await showDatePicker(
            context: context,
            initialDate: selectedDate,
            firstDate: DateTime(2000),
            lastDate: DateTime(2101)
         );
    
         if (pickedDate != null) {
          setState(() {
            selectedDate = pickedDate;
            // Update selectedDate, so that now the new selected date acts
            // as the initial selected value
           });
         }
    ...
    

    Ensure that you are using StatefulWidget and declaring the selectedDate variable as shown below:

    
    class _MyWidgetState extends State<MyWidget> {
       DateTime selectedDate = DateTime.now();
     ...
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search