简体   繁体   English

在 flutter 中按下后如何更改 IconButton 的颜色

[英]how to change color of IconButton after pressed in flutter

I want to change color of icon after pressing.我想在按下后更改图标的颜色。 how can I do it?我该怎么做? My IconButton is leading of a ListTile .我的IconButton领先于ListTile

leading: new IconButton(
  icon: Icon(Icons.star, color: Colors.white),
  onPressed: () {
    setState(() {
      //color: Colors.yellow; //How?

    });
  },
),

You could do something like this你可以做这样的事情

class SomeState extends State<StatefulWidget> {
  Color _iconColor = Colors.white;

  @override
  Widget build(BuildContext) {
    return ListTile(
      leading: new IconButton(
        icon: Icon(Icons.star, color: _iconColor),
        onPressed: () {
          setState(() {
          _iconColor = Colors.yellow;
        });
      },
    );
  }
}

the answer above is correct but i want to add if the user clicked again color will stay the same so you may want to change the color to the original color on the second tap, i though its worth mentioning上面的答案是正确的,但我想补充一点,如果用户再次单击颜色将保持不变,因此您可能希望在第二次点击时将颜色更改为原始颜色,但值得一提

class SomeState extends State<StatefulWidget> {
  Color _favIconColor = Colors.grey;
  @override
  Widget build(BuildContext) {
    return ListTile(
      child: IconButton(
                      icon: Icon(Icons.favorite),
                      color: _favIconColor,
                      tooltip: 'Add to favorite',
                      onPressed: () {
                        setState(() {
                          if(_favIconColor == Colors.grey){
                            _favIconColor = Colors.red;
                          }else{
                        _favIconColor = Colors.grey;
                    }
               });
            },
          ),
       );
     }
    }

You can create a Boolean and then Give color according to that, this will remove the issue of using ifElse.你可以创建一个 Boolean 然后根据它给颜色,这将消除使用 ifElse 的问题。 here is how You can do this你可以这样做

class SomeState extends State<StatefulWidget> {
bool _isTap = false;//using false as initial value(not tapped)

@override
Widget build(BuildContext) {
return ListTile(
  leading: new IconButton(
    icon: Icon(Icons.star, color: _isTap?Colors.white:Colors.grey),
    onPressed: () {
      setState(() {
      _onTap =!_onTap;
// we are using ! because it changes values to both conditions
// true->false <-> false->true
     });
    },
  );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM