Reputation: 1
I want to change the favorite icon and its color when pressed
class MyFavorite extends ChangeNotifier{
bool isFavorite ;
isFavorited(){
isFavorite = !isFavorite;
notifyListeners();
}
}
var favorite = Provider.of<MyFavorite>(context , listen: false);
GestureDetector(
onTap: () {
favorite.isFavorited();
},
child: Icon(favorite.isFavorite == true ? Icons.favorite :Icons.favorite_border, color: favorite.isFavorite == true ? Colors.red : Colors.white,
)),
and when I try to set the listen to true when I clicked the color changed for other items
Upvotes: 0
Views: 552
Reputation: 744
There are a few things you need/should do. First, you need to give the boolean an initial value. Secondly, it is advised to modify your properties as getters, but in doing so, it then makes sense to make them private first(indicated by the underscore). This is recommended so that they will not be able to be accessed from outside and modified. Lastly, you need to take off the listen: false
because you are actually trying to change the UI by rebuilding the widget.
bool _isFavorite = false;
bool get isFav => _isFavorite;
isFavorited(){
_isFavorite = !_isFavorite;
notifyListeners();
}
var favorite = Provider.of<MyFavorite>(context);
GestureDetector(
onTap: () {
favorite.isFavorited();
},
child: Icon(favorite.isFav == true ? Icons.favorite :Icons.favorite_border, color: favorite.isFav == true ? Colors.red : Colors.white,
)),
enter code here
As noted in the comments, you can just use favorite.isFav
for the condition without the == true
I highly reccomend you to read this https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple
Upvotes: 1
Reputation: 4391
Initialize your isFavourite
variable in the class as true
or false
.
like this:-
class MyFavorite extends ChangeNotifier{
bool isFavorite =false;
isFavorited(){
isFavorite = !isFavorite;
notifyListeners();
}
}
Put this line in the build
function (if it's not already there) and remove the listen: false
var favorite = Provider.of<MyFavorite>(context);
listen:false
meaning you don't want to listen for upcoming changes.
Upvotes: 0