需求:实现一个搜索界面,输入关键词搜索,列表显示返回的搜索结果,需将搜索结果中的关键词标红显示
实现:
RichText(
text: TextSpan(children: getTextSpans()),
softWrap: true,
),
List<TextSpan> getTextSpans() {
List<TextSpan> spans = [];
int index = 0;
String name = widget.user.nickName ?? '';
while (index < name.length) {
int current = 0;
bool flag = false;
while (current < widget.notifier.searchString.length) {
if (name[index] == widget.notifier.searchString[current]) {
spans.add(
TextSpan(
text: name[index],
style: TextStyle.normal(
fontSize: themeData.fontSizeSubHead,
textColor: themeData.brandImportant,
isBold: true),
),
);
flag = true;
break;
}
current++;
}
if (flag) {
index++;
continue;
}
spans.add(
TextSpan(
text: name[index],
style: TextStyle.normal(
fontSize: themeData.fontSizeSubHead,
textColor: themeData.colorTextBase,
isBold: true),
),
);
index++;
}
return spans;
}
将搜索结果中的字符一个一个取出与搜索字串比对,如比中则标红显示,未比中则常规显示。