如何在Flutter中悬停文本?

db2dz4w8  于 2022-12-19  发布在  Flutter
关注(0)|答案(3)|浏览(178)

嗨,我想用Flutter来为我的文本悬停颜色。但是我不知道怎么做。有人能告诉我怎么做吗?这是我的代码...

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

lvmkulzt1#

我为此效果编写了“HoverBuilder”小部件

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;
    });
  }
}

然后按如下所示 Package 微件

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',        
      ),
    );
  },
)
h6my8fg2

h6my8fg22#

用户MouseRegion负责悬停小部件

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',           
    )),
 ),
7cwmlq89

7cwmlq893#

使用Tooltip

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static const String _title = 'Tooltip Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: TooltipSample(),
        ),
      ),
    );
  }
}

class TooltipSample extends StatelessWidget {
  const TooltipSample({super.key});

  @override
  Widget build(BuildContext context) {
    return const Tooltip(
      message: 'I am a Tooltip',
      child: Text('Hover over the text to show a tooltip.'),
    );
  }
}

相关问题