0

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.

  • Why is _showPauseIcon and doSomething not in the setState function? You should put those in setState – flutterloop Mar 30 '22 at 13:26
  • If I put _showPauseIcon and the call to doSomething() inside the setState function, it doesn't make any difference. – user18632221 Mar 30 '22 at 13:33
  • are these built in the build method tree? Could you show the entire code – flutterloop Mar 30 '22 at 13:38
  • please show the entire code, also what you want exactly provide via image or gif file – MohammedAli Mar 30 '22 at 13:40
  • I've read the notes on adding code to stack overflow comments, but can't get it to work yet... It doesn't appear to matter whether the code is inside or outside the setState function. It's easy to prove that setState is being called asyncronously by Flutter by adding `Future executeAfterBuild() async { print("executeAfterBuild()"); }` before the widget build function. And inside the widget build function: ` @override Widget build(BuildContext context) { executeAfterBuild();` – user18632221 Mar 30 '22 at 13:53
  • https://stackoverflow.com/questions/48844804/flutter-setstate-not-updating-inner-stateful-widget check out this question and see if it helps. – flutterloop Mar 30 '22 at 14:24

2 Answers2

0

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();
 },
)
Vishal_VE
  • 1,852
  • 1
  • 6
  • 9
0

Solved:

onPressed: () {
        
    setState(() {
       _showPauseIcon = true;
    });
        
    SchedulerBinding.instance.addPostFrameCallback((_) {  
        doSomething();
    });
    
}
  • Some further background info: https://stackoverflow.com/questions/59555999/flutter-setstate-doesnt-execute-until-the-enclosing-function-returns – user18632221 Mar 30 '22 at 19:13