Search code examples
flutterdartwidgetmousehovergesturedetector

How to persist a hover effect on a widget when moving the mouse to click on a child widget?


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:

enter image description here

The edit icon should persist even when I stop hovering over the container to click on it.

Desired Result:

enter image description here

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.


Solution

  • Inside your AddProyectName() the if condition, which is ->

    if (_isHovered && widget.isEditable){}
    

    Based on this condition we just showing the edit icon and the "edit message".

    For desired result, We need to show the icon always if "isEditable = true" and wrap that Icon with a Container so that we can change the background color on hover.

    For the "edit message", we can use ToolTip().

    Here's an example:

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() async {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeData(useMaterial3: false),
          home: const TestApp(),
        );
      }
    }
    
    class TestApp extends StatefulWidget {
      const TestApp({super.key});
    
      @override
      State<TestApp> createState() => _TestAppState();
    }
    
    class _TestAppState extends State<TestApp> {
      bool _isEditIconVisible = false;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.black,
          body: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              setState(() => _isEditIconVisible = false);
            },
            child: Center(
              child: AddProyectName(
                const Color(0xffDE6868),
                index: 0,
                isEditable: true,
                isEditIconVisible: _isEditIconVisible,
                
                onEnterContainerHover: (p0) {
                  setState(() => _isEditIconVisible = true);
                },
                onExitContainerHover: (p0) {
                  setState(() => _isEditIconVisible = false);
                },
              ),
            ),
          ),
        );
      }
    }
    
    class AddProyectName extends StatefulWidget {
      final Color color;
      final int index;
      final bool isEditable;
      final bool isEditIconVisible;
    
      final Function(PointerEnterEvent)? onEnterContainerHover;
      final Function(PointerExitEvent)? onExitContainerHover;
    
      const AddProyectName(this.color,
          {required this.index,
          this.isEditable = false,
          super.key,
          required this.isEditIconVisible,
          this.onEnterContainerHover,
          this.onExitContainerHover});
    
      @override
      State<AddProyectName> createState() => _AddProyectNameState();
    }
    
    class _AddProyectNameState extends State<AddProyectName> {
      bool _isHovered = false;
    
      @override
      Widget build(BuildContext context) {
        return MouseRegion(
          onEnter: widget.onEnterContainerHover,
          onExit: widget.onExitContainerHover,
          child: Container(
            height: 100,
            width: MediaQuery.sizeOf(context).width * 0.50,
         
            decoration: BoxDecoration(border: Border.all(color: Colors.white)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Visibility(
                        visible: widget.isEditIconVisible,
                        replacement: const SizedBox(
                          height: 40,
                          width: 40,
                        ),
                        child: MouseRegion(
                          onEnter: (_) => setState(() => _isHovered = true),
                          onExit: (_) => setState(() => _isHovered = false),
                          cursor: SystemMouseCursors.click,
                          child: Tooltip(
                            message: "Edit Message",
                            decoration: BoxDecoration(
                              color: Colors.black,
                              borderRadius: BorderRadius.circular(4.0),
                            ),
                            child: Container(
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: _isHovered
                                    ? Colors.white30
                                    : Colors.transparent,
                              ),
                              height: 40,
                              width: 40,
                              child: const Icon(Icons.edit,
                                  color: Colors.white, size: 20),
                            ),
                          ),
                        )),
                  ],
                ),
                const SizedBox(width: 10),
                Container(
                  width: 100,
                  height: 100,
                  color: const Color(0xffDE6868),
                ),
              ],
            ),
          ),
        );
      }
    }
    

    Here's the updated output: updated_video