按下时更改浮动按钮图标的方法

时间:2018-02-08 03:38:20

标签: dart flutter

按下时有没有办法更改浮动按钮的图标? 代码:

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));

2 个答案:

答案 0 :(得分:6)

您可以使用状态变量在图标之间切换。

示例:

bool playing = false;

然后

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));

希望有所帮助!

答案 1 :(得分:0)

您还可以使用枚举 enum 来定义命名常量值。

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

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

现在,您可以在代码中的任何位置使用selectedGender Dart条件运算符(?:)。

相关问题