Search code examples
flutterbuttonhovertint

Tint image on hover/pressed


I have a button widget that accepts a text and an and icon. I want to tint the image when a user hover/taps the button. How can I achieve this? I don't want a ripple effect just a white tint.

class SquareButton extends StatelessWidget {
  final String icon;
  final String text;

  SquareButton(this.icon, this.text);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () { print(text); },
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            Image(
              image: AssetImage(icon),
              fit: BoxFit.cover,
            ),
            Container(
                height: 30,
                child: Text(
                  text,
                  style: TextStyle(
                      color: Colors.white,
                      fontStyle: FontStyle.italic
                  ),
                )
            ),
          ],
        )
    );
  }
}

Solution

  • One way you can try is something like this.

    class SquareButton extends StatefulWidget {
      final String icon;
      final String text;
    
      SquareButton(this.icon, this.text);
    
      @override
      _SquareButtonState createState() => _SquareButtonState();
    }
    
    class _SquareButtonState extends State<SquareButton> {
      bool isTapped = false;
    
      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          onTapDown: (_) {
            setState(() {
              isTapped = true;
            });
          },
          onTapUp: (_) {
            setState(() {
              isTapped = false;
            });
          },
          onTap: () { print(widget.text); },
          child: Stack(
            alignment: Alignment.bottomCenter,
            children: [
              Image.asset(
                widget.icon,
                fit: BoxFit.cover,
                color: isTapped ? Colors.white : null,
              ),
              Container(height: 30, child: Text(widget.text, style: TextStyle(color: Colors.white, fontStyle: FontStyle.italic,),),),
            ],
          ),
        );
      }
    }