在Flutter中实现悬停效果(Hover Effect)主要有以下几种方式:
1. 使用 InkWell 或 GestureDetector(基础悬停)
InkWell(
onHover: (isHovering) {
// isHovering 为 true 时表示鼠标悬停
setState(() {
_isHovered = isHovering;
});
},
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: _isHovered ? Colors.blue : Colors.grey,
borderRadius: BorderRadius.circular(8),
),
child: Text('悬停按钮'),
),
)
2. 使用 MouseRegion(推荐)
bool _isHovered = false;
MouseRegion(
onEnter: (_) => setState(() => _isHovered = true),
onExit: (_) => setState(() => _isHovered = false),
child: AnimatedContainer(
duration: Duration(milliseconds: 200),
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: _isHovered ? Colors.blue : Colors.grey,
borderRadius: BorderRadius.circular(8),
),
child: Text('悬停效果'),
),
)
3. 使用 HoverButton(第三方包)
首先添加依赖:
dependencies:
hovering: ^0.2.0
使用:
HoverButton(
onPressed: () {},
hoverColor: Colors.blue.withOpacity(0.1),
child: Text('悬停按钮'),
)
4. 自定义悬停组件
class HoverWidget extends StatefulWidget {
@override
_HoverWidgetState createState() => _HoverWidgetState();
}
class _HoverWidgetState extends State<HoverWidget> {
bool _isHovered = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: (_) => setState(() => _isHovered = true),
onExit: (_) => setState(() => _isHovered = false),
child: Transform.scale(
scale: _isHovered ? 1.05 : 1.0,
child: AnimatedContainer(
duration: Duration(milliseconds: 200),
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: _isHovered ? Colors.blue : Colors.grey,
boxShadow: _isHovered ? [
BoxShadow(
color: Colors.blue.withOpacity(0.3),
blurRadius: 10,
offset: Offset(0, 5),
)
] : [],
),
child: Text('自定义悬停'),
),
),
);
}
}
推荐使用 MouseRegion,因为它专门用于处理鼠标事件,性能更好且易于控制。结合 AnimatedContainer 可以实现流畅的动画效果。