I would like to change the color of an icon after pressing it, but it seems the following code doesn't work.
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);
}
Currently, if I press the icon, its color will not change, I have to go back to its parent, then re-enter. I am wondering how to change its color immediately, Thanks.
update:
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));
}),
);
}
You can simply put a condition for each color :
color:(isPressed) ? Color(0xff007397)
: Color(0xff9A9A9A))
and in the onPressed function :
onPressed: ()
{
setState(()
{
isPressed= true;
});
}
You need to use setState() function. Wherever you are updating your variable values.
For example, I want to update my _newVar value to newValue and this should be updated into the view then instead of writing
_newVar = newValue;
it should be:
setState(() {
_newVar = newValue;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With