'Flutter – How to change appbar's selected icon onpressed and deselect it automatically when another icon is selected?
I'm new to flutter. I have an appbar with 5 IconButton. I want to change the icon of the IconButton and its color when pressed, and automatically undo the changes when another IconButton is pressed. Help me please.
Solution 1:[1]
first, create a List boolean to store the state of icons
false = deselected , true = selected
List<bool> isPressed = [false, false, false, false, false];
create a function to set the list to the initial value
getInitial() {
List<bool> isPressed = [false, false, false, false, false];
return isPressed;
}
whenever you tap on the icon :
isPressed = getInitial();// set the list to initial values so that all the icons will be reset to default colour.isPressed[index] = true;//the setthe specific index to true so that specific icon will change the colour
here is the implementation code: hope you got it ?
AppBar(
title: const Text("hello world"),
actions: [
GestureDetector(
onTap: () {
setState(() {
if (isPressed[0] == false) {
isPressed = getInitial();
isPressed[0] = true;
} else
isPressed[0] = false;
});
},
child: Icon(
Icons.favorite,
color: isPressed[0] == false ? Colors.white : Colors.red,
),
),
GestureDetector(
onTap: () {
setState(() {
if (isPressed[1] == false) {
isPressed = getInitial();
isPressed[1] = true;
} else
isPressed[1] = false;
});
},
child: Icon(
Icons.favorite,
color: isPressed[1] == false ? Colors.white : Colors.red,
),
)
],
),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
