Flutter Web-悬停时如何更改Flatbutton TEXT颜色

问题描述

您好,我正在Flutter网站上工作,当我悬停平面按钮时,我想更改文本颜色。悬停时不按。但是我如何检测/知道它已经被悬停了,所以我可以管理状态颜色。谢谢

FlatButton(
              color: Colors.white,textColor: Colors.teal[700],//when hovered text color change
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5),side: BorderSide(
                  color: Colors.teal[700],),onpressed: () {},child: Text("Log in"),

解决方法

您可以在下面复制粘贴运行完整代码
您可以使用MouseRegion的{​​{1}}属性

代码段

onHover

工作演示

enter image description here

完整代码

void _incrementExit(PointerEvent details) {
    setState(() {
      textColor = Colors.blue;
      _exitCounter++;
    });
  }

void _updateLocation(PointerEvent details) {
    setState(() {
      textColor = Colors.red;
      x = details.position.dx;
      y = details.position.dy;
    });
  }
  
return MouseRegion(
      onEnter: _incrementEnter,onHover: _updateLocation,onExit: _incrementExit,child: FlatButton(
        color: Colors.white,textColor: Colors.teal[700],//when hovered text color change
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5),
,

对于 textButton,我们可以使用 foregroundColorButtonStyle 属性。

TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.focused))
  return Colors.red;
if (states.contains(MaterialState.hovered))
    return Colors.green;
if (states.contains(MaterialState.pressed))
    return Colors.blue;
return Colors.yellow; // null throus error in flutter 2.2+.
}),),onPressed: () { },child: Text('TextButton with custom overlay colors'),)
,

也有一个使用MouseRegion实现此功能的软件包。

https://pub.dev/packages/hovering

示例:

HoverButton(
  onpressed: () {​​​​​​
    print('test');
  }​​​​​​,color: Colors.green,hoverColor: Colors.red,hoverTextColor: Colors.blue,child: Text('test'),)
,

您可以像这样更改按钮样式的 foregroundColor 属性:

ElevatedButton.styleFrom().copyWith(
      backgroundColor: MaterialStateProperty.resolveWith<Color?>(
        (states) {
          if (states.contains(MaterialState.hovered)) {
            return Colors.blue;
          } else if (states.contains(MaterialState.pressed)) {
            return Colors.yellow;
          }
          return Colors.red;
        },foregroundColor: MaterialStateProperty.resolveWith<Color?>(
        (states) {
          if (states.contains(MaterialState.hovered)) {
            return Colors.green;
          }
          return Colors.black;
        },);