Flutter学习之旅 - 多行文本全文展开, 关键字高亮

功能需求:
- 设置文本最多显示行数,超过指定行数显示展开按钮
- 展开/隐藏按钮
- 文字高亮显示:支持对设置的关键字进行高亮显示,支持多个关键字
效果图如下:

构造方法:
const ExpandableText(
this.text, {
Key key,
this.expandText,
this.collapseText,
this.expandColor,
this.collapseColor,
this.expandImage,
this.collapseImage,
this.imageHeight,
this.imageWidth,
this.expandView,
this.collapseView,
this.expanded = false,
this.style,
this.textDirection,
this.textAlign,
this.textScaleFactor,
this.maxLines = 2,
this.semanticsLabel,
this.keywords,
this.keywordColor,
}) : assert(text != null),
assert((expandText != null &&
collapseText != null &&
expandColor != null &&
collapseColor != null) ||
(expandView != null && collapseView != null)),
assert(expanded != null),
assert(maxLines != null && maxLines > 0),
assert(expandImage == null ||
collapseImage == null ||
(expandImage != null &&
collapseImage != null &&
imageHeight != null &&
imageWidth != null)),
super(key: key);
/// 文本内容
final String text;
/// 展开文字
final String expandText;
/// 收起文字
final String collapseText;
/// 是否展开
final bool expanded;
/// 展开文字颜色
final Color expandColor;
/// 收起文字颜色
final Color collapseColor;
/// 展开图片路径
final String expandImage;
/// 收起图片路径
final String collapseImage;
/// 图片高度
final double imageHeight;
/// 图片宽度
final double imageWidth;
/// 文字样式
final TextStyle style;
final TextDirection textDirection;
final TextAlign textAlign;
final double textScaleFactor;
/// 最大行数
final int maxLines;
/// 扩展View
final Widget expandView;
final Widget collapseView;
final String semanticsLabel;
/// 改变颜色文本的集合
final List<String> keywords;
/// 改变后的颜色
final Color keywordColor;
实现思路:
- 构建Span
final linkText =
_expanded ? ' ${widget.collapseText}' : '${widget.expandText}';
// 展开 隐藏的文本颜色
final linkColor = _expanded ? widget.collapseColor : widget.expandColor;
/// 构建展开或隐藏的TextSpan
final link = TextSpan(
text: linkText,
style: effectiveTextStyle.copyWith(
color: linkColor,
),