Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why setstate works on second button click flutter

I am calculating pregnancy weeks .but the set state only update on second click.

 ElevatedButton (
            onPressed: () {
             setState(() {
               _selectDate(context);


               sDate = selectedDate;
               dueDate = sDate.add(Duration(days: DAYS_IN_PREGNANCY));
               DateTime today = DateTime.now();
               remaining = today.difference(dueDate).inDays.abs();
               daysIn = DAYS_IN_PREGNANCY - remaining;
               weekPart = daysIn % 7;
               weekValue = daysIn / 7;
               week = weekValue + "." + weekPart;             });

            },
            child: const Text("Choose Date"),
          ),
_selectDate(BuildContext context) async {
     final DateTime? selected = await showDatePicker(
          context: context,
          initialDate: selectedDate,
          firstDate: DateTime(2010),
          lastDate: DateTime(2025),
     );
     setState(() {});
     selectedDate = selected!;
} 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As you can see, your _selectDate function is async and you need to await for it and also you don’t need to call setState inside _selectDate, so change you click to this:

 ElevatedButton (
        onPressed: () async{ //<--- add this
         sDate = await  _selectDate(context); //<--- add this
         setState(() {
           dueDate = sDate.add(Duration(days: DAYS_IN_PREGNANCY));
           DateTime today = DateTime.now();
           remaining = today.difference(dueDate).inDays.abs();
           daysIn = DAYS_IN_PREGNANCY - remaining;
           weekPart = daysIn % 7;
           weekValue = daysIn / 7;
           week = weekValue + "." + weekPart;
         });

        },
        child: const Text("Choose Date"),
    ),

and change your _selectDate to this:

DateTime? _selectDate(BuildContext context) async {
     final DateTime? selected = await showDatePicker(
          context: context,
          initialDate: selectedDate,
          firstDate: DateTime(2010),
          lastDate: DateTime(2025),
     );
     
     return selected;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading