Home > Software design >  How can I hover text in Flutter?
How can I hover text in Flutter?

Time:09-20

Hi I want to hover color for my text by using Flutter. But I don't know how. Can anyone show me how to do it? This is my code....

Text(
                            "Lorem ipsum dolor sit amet,\n consectetur adipiscing elit.",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 10,
                              fontFamily: 'Poppins',
                            
                            )),

CodePudding user response:

I wrote the "HoverBuilder" widget for this effect

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class HoverBuilder extends StatefulWidget {
  const HoverBuilder({
    required this.builder,
    Key? key,
  }) : super(key: key);

  final Widget Function(bool isHovered) builder;

  @override
  _HoverBuilderState createState() => _HoverBuilderState();
}

class _HoverBuilderState extends State<HoverBuilder> {
  bool _isHovered = false;
  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (PointerEnterEvent event) => _onHoverChanged(enabled: true),
      onExit: (PointerExitEvent event) => _onHoverChanged(enabled: false),
      child: widget.builder(_isHovered),
    );
  }

  void _onHoverChanged({required bool enabled}) {
    setState(() {
      _isHovered = enabled;
    });
  }
}

Then wrap the widget as follows

HoverBuilder(
  builder: (isHovered) {
    return Text(
      "Lorem ipsum dolor sit amet,\n consectetur adipiscing elit.",
      style: TextStyle(
        color: isHovered ? Colors.white : Colors.grey,
        fontSize: 10,
        fontFamily: 'Poppins',        
      ),
    );
  },
)

CodePudding user response:

User MouseRegion for hover widget

MouseRegion(
  onEnter: (_) {
     //hover
  },
  onExit: (_) {
     //exit hover
  },
  child: Text(
    "Lorem ipsum dolor sit amet,\n consectetur adipiscing elit.",
    style: TextStyle(
      color: Colors.white,
      fontSize: 10,
      fontFamily: 'Poppins',           
    )),
 ),
  • Related