在Flutter中更改”Like”按钮的颜色。

huangapple go评论68阅读模式
英文:

Changing Like Button Color in Flutter

问题

我尝试在按下时更改IconButton的图标形状和颜色,但没有任何反应。以下是我的代码:

String adTitle = widget.documentSnapshot['Title'];
String $adDescription = widget.documentSnapshot['Description'];

IconData _iconData = Icons.favorite_border_outlined;
Color _iconColor = Colors.red;

return Scaffold(
  body: Column(
    children: [ 
      Row(
        children: [
          IconButton(
            icon: Icon(
              _iconData,
              size: 40,
              color: _iconColor,
            ),
            onPressed: () {
              setState(() {
                _iconData = Icons.favorite;
                _iconColor = Colors.blue;
              });
            },
          )
        ],
      ),
    ],
  ),
);
英文:

I try to change the icon shape and color of the IconButton when it is pressed but there is nothing happens. here is my code:

 String adTitle = widget.documentSnapshot['Title'];
String $adDescription = widget.documentSnapshot['Description'];

IconData _iconData = Icons.favorite_border_outlined;
Color _iconColor = Colors.red;

return Scaffold(
  body: Column(
    children: [ 
      Row(
        children: [
          IconButton.outlined(
            icon: Icon(
              _iconData,
              size: 40,
              color: _iconColor,
            ),
            onPressed: () {
              setState(() {
                _iconData = Icons.favorite;
                _iconColor = Colors.blue;
              });
            },
          )
        ],
      ),
    ],
  ),
);
}

答案1

得分: 2

IconData _iconData = Icons.favorite_border_outlined;
Color _iconColor = Colors.red;

它们目前是局部变量。要使其正常工作,您需要将它们定义为类级别的变量(在build方法之外定义它们)。


<details>
<summary>英文:</summary>

IconData _iconData = Icons.favorite_border_outlined;
Color _iconColor = Colors.red;


They are local variables as of now. You need to make them class level varibales for this to work (define them outside build method)

</details>



huangapple
  • 本文由 发表于 2023年6月6日 17:26:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76413215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定