Home > OS >  How do I update a widget UI on button press then execute a function in Flutter?
How do I update a widget UI on button press then execute a function in Flutter?

Time:03-31

When a widget icon button is pressed, I want to change the button's icon, have setState rebuild the widget so the changed button icon is visible, then run a function:

bool _showPauseIcon = false;

void doSomething() {
 print("doSomething()");
}

.
.
.

IconButton(
 icon: _showPauseIcon ? Icon(Icons.pause) : Icon(Icons.play),
 onPressed:  () {
    _showPauseIcon = true;
    setState (() { });
    doSomething();
 },
)

doSomething() appears to be called before setState rebuilds the widget, so the modified icon only appears after doSomething() has been called - I need it to happen before doSomething() is called. I looking for the simplest possible solution.

CodePudding user response:

SetState is only for the updating the widget on Current page.. So no need to call function inside the setstate.

IconButton(
 icon: _showPauseIcon ? Icon(Icons.pause) : Icon(Icons.play),
 onPressed:  () {
    setState (() {
_showPauseIcon = true;
 });
    doSomething();
 },
)

CodePudding user response:

Solved:

onPressed: () {
        
    setState(() {
       _showPauseIcon = true;
    });
        
    SchedulerBinding.instance.addPostFrameCallback((_) {  
        doSomething();
    });
    
}
  • Related