Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Dart - setState does not reload state when using with Future<> for the async function

I have a Flutter code with setState() for the RaisedButton, working fine to change all the local variables like changing button color, hide/show other components on the same page etc. But when I use Future statusCode = myFun(); where myFun() is Async function, Future always returns code properly by setState() takes effect every 2nd time.

My code is here:

return RaisedButton(
    color: infBtnColor ? Colors.green : Colors.grey,
    textColor: Colors.black87,
    onPressed: () {
      setState(() {

        infBtnColor = true;    //this takes effect on click properly -always

        Future<int> statusCode = myFun(false);
        statusCode.then((value) {

          if (value == 200) {
            ESPSyncIconColor = true;   // this is to modify other icon from the AppBar
            print("Btn GREEN");
          }
          else {
            ESPSyncIconColor = false;
            print("RED");
          }
        });
      });

    }
);

And the App bar code is here:

AppBar(

    title: Text(title,style: TextStyle(fontSize:18,fontWeight: FontWeight.w300,)),
    backgroundColor: new Color(0xff303030),

    actions: <Widget>[
    Padding(
    padding: EdgeInsets.only(right: 25.0),
    child: Row(
    children: <Widget>[

    Icon(Icons.cloud_upload,size: 26,
    color: (**ESPSyncIconColor**)?Colors.green:Colors.red,

    ),],),),
    ],),

Here I am using variable ESPSyncIconColor to update Icon color from the AppBar of the same page. Which always work on second time, that too with the previous status.

like image 206
Akshay Avatar asked May 30 '26 21:05

Akshay


1 Answers

You are calling a future inside setState. This future isn't going to complete until after setState returns and the widget is rebuilt. Instead, await or then the future and call setState afterward.

onPressed: () {
  infBtnColor = true;
  myFun(false).then((value) {
    setState(() {
      if (value == 200) {
        ESPSyncIconColor = true;   // this is to modify other icon from the AppBar
        print("Btn GREEN");
      } else {
        ESPSyncIconColor = false;
        print("RED");
      }
    });
  });
}
like image 137
Abion47 Avatar answered Jun 01 '26 19:06

Abion47