0
votes

Ok, I am working on a media player app using flutter. Now when I press the play button, it changes to pause button. (Only the icon on the button changes)

The onPressed function for the button changes a boolean value and calls the setState() method.

It goes something like this.

bool _playing = false;  
void _onPlayButtonPressed() {
         setState () {
           if (_playing)
              _playing = false;
           else
              _playing = true;
         }
    }

I also have a function that returns the icon based on the value of _playing.

Widget _playButtonIcon() {

//This function has no setState() call

  if (_playing)
      //return pause icon
  else
      //return play icon
}

Everything works fine. The icon changes everytime I press the button. However as mentioned in docs and also in Flutter Demo App, setState() method calls the build method. Which redraws the entire widget tree including child widgets that are completely unchanged.

Is this approach justified or is this an overkill?

Do I have to put the button on a different Stateful Widget Class and call its build method via setState() everytime I tap this playButton?

What if I have other widgets that also changes the state of UI. Possibly changing different widgets?

What is the proper way to do this without having a performance hit?

1

1 Answers

0
votes

Creating a play button that is a widget of its own with a state that maintains whether it is playing or not definitely makes sense. Now when you call setState on the parent widget it does call the build method, but as far as I know it does not necessarily redraw everything from scratch. If no changes are found in some of the embedded widgets it does not redraw them since they are already in the widget tree. Finally, it is okay to call setstate, however if your app starts getting bigger and you find yourself calling set state in too many places, and want to use global keys, I would advise looking into the Provider package, and making use of the ChangeNotifier/Consumer pattern.