I want to create an effect of changing the icon to its fill version on press on an iconButton, and I am using the selectedIcon option to achieve it. The problem is that the icon is not changing event though I think I have done the right setting. Here it is
IconButton(
isSelected: _homeSelected,
onPressed: () {
setState(() {
_homeSelected = true;
_bookedSelected = false;
_ticketsSelected = false;
_settingsSelected = false;
});
},
icon: const Icon(CupertinoIcons.house),
selectedIcon: const Icon(CupertinoIcons.house_fill),
color: (_homeSelected ? _selectedIconColor : _iconColor),
iconSize: (_homeSelected ? _selectedIconSize : _iconSize),
),
CodePudding user response:
Use Statefulbuilder,when you setstate like this widget rebuild.and initialize its old values. https://api.flutter.dev/flutter/widgets/StatefulBuilder-class.html
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return IconButton(
isSelected: _homeSelected,
onPressed: () {
setState(() {
_homeSelected = true;
_bookedSelected = false;
_ticketsSelected = false;
_settingsSelected = false;
});
},
icon: const Icon(CupertinoIcons.house),
selectedIcon: const Icon(CupertinoIcons.house_fill),
color: (_homeSelected ? _selectedIconColor : _iconColor),
iconSize: (_homeSelected ? _selectedIconSize : _iconSize),
),});
CodePudding user response:
Yo have to change onPressed if you do this(_homeSelected = true) then value is always true so need to change with _homeSelected=!_homeSelected
onPressed: () {
setState(() {
_homeSelected = !_homeSelected;
_bookedSelected = false;
_ticketsSelected = false;
_settingsSelected = false;
});
},