highLightClickableRichText method
Text
highLightClickableRichText({
- required List<
String> keywords, - Color textColor = Colors.black,
- Color highColor = Colors.blue,
- double fontSize = 12,
- double? keywordFontSize,
- FontWeight fontWeight = FontWeight.normal,
- FontWeight? keywordFontWeight,
- void onKeywordTap(
- String keyword
根据关键字创建关键字高亮可点击的富文本widget
keywords 需要高亮可点击的关键字列表
textColor 文本颜色,默认是黑色
highColor 高亮文本颜色,默认是蓝色
fontSize 文本的大小,默认是12
keywordFontSize 高亮文本大小,默认是fontSize大小
fontWeight 文本的字体权重,默认是FontWeight.normal
keywordFontWeight 高亮文本的字体权重,默认是fontWeight
onKeywordTap 高亮文本点击方法回调
Implementation
Text highLightClickableRichText(
{required List<String> keywords,
Color textColor = Colors.black,
Color highColor = Colors.blue,
double fontSize = 12,
double? keywordFontSize,
FontWeight fontWeight = FontWeight.normal,
FontWeight? keywordFontWeight,
void Function(String keyword)? onKeywordTap}) {
keywordFontSize = keywordFontSize ?? fontSize;
keywordFontWeight = keywordFontWeight ?? fontWeight;
List<TextSpan> textSpanList = [];
List<_KeyWordIndex> keywordIndexList = [];
// 找到所有关键字的下标
for (var keyword in keywords) {
keywordIndexList.addAll(_indexOfList(keyword));
}
// 下标升序排序
keywordIndexList.sort((a, b) {
return a.index.compareTo(b.index);
});
int startIndex = 0;
for (var keywordIndex in keywordIndexList) {
var normalText = substring(startIndex, keywordIndex.index);
textSpanList.add(TextSpan(
text: normalText,
style: TextStyle(
color: textColor, fontWeight: fontWeight, fontSize: fontSize)));
var keyword = keywordIndex.keyword;
TapGestureRecognizer? recognizer = onKeywordTap == null
? null
: (TapGestureRecognizer()
..onTap = () {
onKeywordTap(keyword);
});
textSpanList.add(TextSpan(
text: keyword,
style: TextStyle(
color: highColor,
fontWeight: keywordFontWeight,
fontSize: keywordFontSize),
recognizer: recognizer));
startIndex = startIndex + normalText.length + keywordIndex.keyword.length;
}
if (startIndex < length) {
var normalText = substring(startIndex, length);
textSpanList.add(TextSpan(
text: normalText,
style: TextStyle(
color: textColor, fontWeight: fontWeight, fontSize: fontSize)));
}
return Text.rich(
textAlign: TextAlign.left, TextSpan(children: textSpanList));
}