I’m having an issue with a hover effect on a widget in Flutter. When I hover over the container, an edit icon appears. However, when I move my mouse to click on the edit icon, the hover effect disappears, and the edit icon is no longer visible. I want the edit icon to persist even when I stop hovering over the container to click on it.
Problem:
The edit icon should persist even when I stop hovering over the container to click on it.
Desired Result:
Code:
- add_proyects.dart
import 'package:flutter/material.dart';
class AddProyectName extends StatefulWidget {
final Color color;
final int index;
final bool isEditable;
const AddProyectName(this.color, {required this.index, this.isEditable = false, super.key});
@override
State<AddProyectName> createState() => _AddProyectNameState();
}
class _AddProyectNameState extends State<AddProyectName> {
bool _isHovered = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: (_) => setState(() => _isHovered = true),
onExit: (_) => setState(() => _isHovered = false),
cursor: SystemMouseCursors.click,
child: Stack(
fit: StackFit.loose,
clipBehavior: Clip.none,
children: [
Container(
width: 100,
height: 100,
color: widget.color,
),
if (_isHovered && widget.isEditable)
Positioned(
left: -30,
top: 30,
child: GestureDetector(
onTap: () {
print('Edit icon tapped');
},
child: Column(
children: [
Icon(
Icons.edit,
color: Colors.white,
size: 20,
),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(4.0),
),
child: const Text(
'Edit',
style: TextStyle(color: Colors.white, fontSize: 12),
),
),
],
),
),
),
],
),
);
}
}
- task_card.dart
import 'package:flutter/material.dart';
class TaskCard extends StatelessWidget {
const TaskCard({super.key});
@override
Widget build(BuildContext context) {
return Row(
children: [
const AddProyectName(
Color(0xffDE6868),
index: 0,
isEditable: false,
),
const SizedBox(
width: 4,
),
const AddProyectName(
Color(0xffECBB42),
index: 1,
isEditable: false,
),
const SizedBox(
width: 4,
),
const AddProyectName(
Color(0xff4439B9),
index: 2,
isEditable: true,
),
const SizedBox(
width: 4,
),
const AddProyectName(
Color(0xff34BB54),
index: 3,
isEditable: true,
),
],
);
}
}
What I’ve tried:
I’ve tried using MouseRegion
to detect when the mouse enters and exits the container, but it doesn’t seem to work as expected. I’ve also tried using GestureDetector
to detect taps on the edit icon, but it doesn’t persist the hover effect.