我在文本顶部显示工具提示,让用户看到人员的全名,但无论文本是否溢出,它都会显示工具提示:
child: Tooltip(
message: fullNameWithTitle,
child: Text(
fullNameWithTitle,
style: const TextStyle(
color: Colors.white,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
),
),
但是如何设置工具提示,使其在文本被省略号修剪时才显示?
如果有人对这个问题感兴趣,我终于创建了一个可以工作的组件,在 LayoutBuilder 中使用 TextPainter 来检查溢出,然后仅在必要时应用工具提示。 (归功于@Lian 的解释在此主题中
import 'package:flutter/material.dart';
class TextAutoTooltip extends StatelessWidget {
const TextAutoTooltip({
Key? key,
this.text = '',
this.tooltipText,
this.showTooltip = true,
this.maxLines = 1,
this.style,
this.textAlign = TextAlign.left,
this.overflow = TextOverflow.ellipsis,
this.preferBelow = false,
this.verticalOffset,
}) : super(key: key);
/// Text to be displayed
final String? text;
/// Specifiy the text to be displayed for the tooltip (when text is overflowing)
/// If not specified, the tooltip text will be the original text displayed.
final String? tooltipText;
/// Specify whether to display the tooltip when overflowing, or not.
final bool showTooltip;
/// maxLine for the text to be displayed in
final int? maxLines;
/// Style of the text
final TextStyle? style;
/// Text alignment
final TextAlign? textAlign;
/// Text type of overflow
final TextOverflow? overflow;
/// Whether the tooltip defaults to being displayed below the widget.
final bool? preferBelow;
/// Tooltip verticalOffset
final double? verticalOffset;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, size) {
// Creation of a TextSpan
TextSpan span = TextSpan(
text: text,
style: style,
);
// Creation of a TextPainter which will be used to determine whether there is an overflow or not (in fact when max lines will be exceeded)
TextPainter tp = TextPainter(
maxLines: maxLines,
textScaleFactor: MediaQuery.of(context).textScaleFactor, // to be accurate when the device scales font sizes up (or down)
textAlign: TextAlign.left,
textDirection: TextDirection.ltr,
text: span,
);
// The TextPainter is linked to the layout
tp.layout(maxWidth: size.maxWidth);
// Then we get back the overflow info from the TextPainter "didExceedMaxLines" property
bool isOnOverflow = tp.didExceedMaxLines;
return Tooltip(
message: isOnOverflow && showTooltip ? tooltipText ?? text : '',
verticalOffset: verticalOffset,
preferBelow: preferBelow,
child: Text.rich(
span,
overflow: overflow,
maxLines: maxLines,
textAlign: textAlign,
),
);
},
);
}
}
那么它就可以作为经典“文本”组件的系统替代品。