Home > Enterprise >  why setstate works on second button click flutter
why setstate works on second button click flutter

Time:10-13

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!;
} 

CodePudding user response:

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
         var result = await  _selectDate(context); //<--- add this
         if(result != null){ //<--- add this
            setState(() {
               sDate = result; //<--- add this
               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;
}
  • Related