gpt4 book ai didi

flutter - 如何在 flutter 中按下后立即更改图标颜色?

转载 作者:IT王子 更新时间:2023-10-29 06:41:40 25 4
gpt4 key购买 nike

我想在按下图标后改变它的颜色,但似乎下面的代码不起作用。

  void actionClickRow(String key) {
Navigator.of(context).push(
new MaterialPageRoute(builder: (context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(key),
actions: <Widget>[
new IconButton(
icon: new Icon(
Icons.favorite,
color: isSaved(key) ? Colors.red : null, //<--- if key is already saved, then set it to red
),
onPressed: ()
{
setState(() //<--whenever icon is pressed, force redraw the widget
{
pressFavorite(key);
});
}
),
],
),
backgroundColor: Colors.teal,
body: _showContent(key));
}),
);
}


void pressFavorite(String key)
{
if (isSaved(key))
saved_.remove(key);
else
saved_.add(key);
}

bool isSaved(String key) {
return saved_.contains(key);
}

目前,如果我按下图标,它的颜色不会改变,我必须回到它的父级,然后重新进入。我想知道如何立即改变它的颜色,谢谢。

更新:

class MainPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new MainPageState();
}
}


class MainPageState extends State<MainPage> {
bool _alreadySaved;

void actionRowLevel2(String key) {
_alreadySaved = isSaved(key);
Navigator.of(context).push(
new MaterialPageRoute(builder: (context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(key),
actions: <Widget>[
new IconButton(
icon: new Icon(
_alreadySaved ? Icons.favorite : Icons.favorite_border,
color: _alreadySaved ? Colors.red : null,
),
onPressed: ()
{
setState(()
{
pressFavorite(key);
_alreadySaved = isSaved(key); //<--update alreadSaved
});
}
),
],
),
backgroundColor: Colors.teal,
body: _showScript(key));
}),
);
}

最佳答案

您可以简单地为每种颜色设置一个条件:

color:(isPressed) ? Color(0xff007397)
: Color(0xff9A9A9A))

在 onPressed 函数中:

 onPressed: ()
{
setState(()
{
isPressed= true;
});
}

关于flutter - 如何在 flutter 中按下后立即更改图标颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com