I have 3 icons for example and I want to Change the Color of the hovered one without creating variable for every icon ,** I'm using "Mouse Region" Widget and when I hover an icon it Hovers another one too ... here is my Code:
MouseRegion(
onHover: (event) => {
setState((){
isHover=true;
})
},
onExit: (event)=>{
setState((){
isHover=false;
})
},
child: Icon(FontAwesomeIcons.instagram,color: isHover ? Color(0xFF54b981) : Colors.white,))),
CodePudding user response:
You can solve this by 2 options
Create 3 different variables and save each icons hover state in respective variable
Extract this widget to a new stateful widget add all logic in it and use that class..
Option 2 is a good practice to follow.
CodePudding user response:
You can track hover index with single nullable int. Creating separate widget a good option.
class SF extends StatefulWidget {
const SF({Key? key}) : super(key: key);
@override
State<SF> createState() => _SFState();
}
class _SFState extends State<SF> {
int? hoveredIndex;
_onExit(_) {
setState(() {
hoveredIndex = null;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.purple,
body: Column(
children: [
MouseRegion(
onEnter: (event) {
setState(() {
hoveredIndex = 0;
});
},
onExit: _onExit,
child: Icon(
FontAwesomeIcons.instagram,
color: hoveredIndex == 0 ? Color(0xFF54b981) : Colors.white,
),
),
MouseRegion(
onEnter: (event) {
setState(() {
hoveredIndex = 1;
});
},
onExit: _onExit,
child: Icon(
FontAwesomeIcons.instagram,
color: hoveredIndex == 1 ? Color(0xFF54b981) : Colors.white,
),
),
],
),
);
}
}