Home > Software engineering >  onHover effect doesn't work on TextButton nor InkWell
onHover effect doesn't work on TextButton nor InkWell

Time:12-19

I am developing a Flutter website. I have some links that I want to behave as a normal link: with a different color when the user hovers over them. However, I can't manage to make the color change.

I have tried using a TextButton with the onHover property. I have also tried with an Inkwell onHover property and hoverColor. I have wrapped the InkWell with Material and my onTap function is defined. I have also tried by wrapping this on an AnimatedContainer, but nothing seems to work.

Here is my code.

TextStyle? bodyTextStyle = Theme.of(context).textTheme.bodySmall;

InkWell(
  color: Colors.transparent,
  child: Text(
    "data policy",
    style: bodyTextStyle,
  ),
  onTap: () => Navigator.of(context).pushNamed(
    Navigation(context).routes["data policy"]),
  onHover: (isHovering) {
    setState(() {
      bodyTextStyle = isHovering
          ? bodyTextStyle?.copyWith(
              color: Theme.of(context).colorScheme.outline)
          : bodyTextStyle;
    });
  },
),

I prefer using InkWell rather than TextButton in order to get rid of the shadow around the text that TextButton creates.

CodePudding user response:

You can follow this snippet, hoverColor from InkWell can overlap.

InkWell(
  child: SizedBox(
      width: 100,
      height: 100,
      child: Text(
        "Text",
        style: linkTextStyle,
      )),
  onTap: () {},
  hoverColor: Colors.transparent, //button splash color
  onHover: (isHovering) {
    linkTextStyle = isHovering
        ? TextStyle(color: Colors.red)
        : TextStyle(color: Colors.cyanAccent);
    setState(() {});
  },
),

Also You can check MouseRegion, elevation on buttonStyle.

CodePudding user response:

You can also trying to use a TextButton. If I understood you correct a TextButton like this has the same functionality you described:

TextButton(
        style: ButtonStyle(
          foregroundColor: MaterialStateProperty.resolveWith<Color>(
                  (Set<MaterialState> states) {
                if (states.contains(MaterialState.hovered))
                  return Colors.green;
                return Colors
                    .red;
              }),
        ),

        onPressed: () {},
        child: const Text('Save'),
      ),
  • Related