Search code examples
flutterdartflutter-layout

how to change only hovered icon Color in Flutter


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,))),

Solution

  • 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,
                ),
              ),
            ],
          ),
        );
      }
    }