【发布时间】:2025-12-23 10:30:10
【问题描述】:
我想在按下后更改图标的颜色,但是下面的代码似乎不起作用。
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));
}),
);
}
【问题讨论】:
-
你确定你有扩展 statefulwidget 吗?
-
@ArnoldParge 是的,MainPage 扩展了 StatefulWidget
标签: flutter