Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to change floating button icon when pressed

Tags:

flutter

dart

Is there any way to change the floating button's icon when pressed? Code:

var musicButton = new FloatingActionButton(
    onPressed: (){
      if(playerState == PlayerState.playing) {
        //setState(() => child = new Icon(Icons.pause));
        setState((){
          child: new Icon(Icons.play_arrow);
        });
        pause();
      } else if (playerState == PlayerState.paused){
        setState((){
          child: new Icon(Icons.pause);
        });
        play();
      }
    },
    tooltip: 'Play Music',
    child: new Icon(Icons.pause));
like image 405
Arvin Avatar asked Feb 08 '18 03:02

Arvin


2 Answers

You can just use a state variable to switch between icons.

Example:

bool playing = false;

then

var musicButton = new FloatingActionButton(
    onPressed: (){
      if(playerState == PlayerState.playing) {
        setState((){
          playing = false;
        });
        pause();
      } else if (playerState == PlayerState.paused){
        setState((){
          playing = true;
        });
        play();
      }
    },
    tooltip: 'Play Music',
    child: playing?new Icon(Icons.pause):new Icon(Icons.play_arrow));

Hope that helped!

like image 64
Hemanth Raj Avatar answered Oct 12 '22 15:10

Hemanth Raj


You can use enumeration also enum used to define named constant values.

enum Gender {Male,Female,} // enum definition globally
Gender selectedGender;    // enum declaration

onPress: () {
             setState(() {
             selectedGender = Gender.Male;
              });
            },

Now you can use selectedGender Dart Conditional Operators ( ? : ) anywhere in your code.

like image 22
Ayon Moitra Avatar answered Oct 12 '22 14:10

Ayon Moitra