Я хотел бы изменить цвет значка после нажатия на него, но, похоже, следующий код не работает.
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));
}),
);
}