gpt4 book ai didi

flutter - 如何在 searchDelegate 上突出显示正确的单词?

转载 作者:IT王子 更新时间:2023-10-29 06:36:51 25 4
gpt4 key购买 nike

我突出显示了这个词,但不是正确的词。

在我的 BuilderSuggection 中,我添加了这样的代码,

check my searchDelegate

 title: RichText(
text: TextSpan(
text: suggestList[index].d.substring(0, query.length),
style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold),
children: [
TextSpan(
text: suggestList[index].d.substring(query.length),
style: TextStyle(color: Colors.grey))
])),

最佳答案

我编写了一个返回 TextSpan 列表的快速函数。

函数将查询字符串与源字符串进行匹配,一个接一个地枚举匹配项,将源字符串分成几部分:匹配之前、匹配之后以及匹配本身 - 将其设为粗体。

它旨在用于 RichText 小部件。

List<TextSpan> highlightOccurrences(String source, String query) {
if (query == null || query.isEmpty || !source.toLowerCase().contains(query.toLowerCase())) {
return [ TextSpan(text: source) ];
}
final matches = query.toLowerCase().allMatches(source.toLowerCase());

int lastMatchEnd = 0;

final List<TextSpan> children = [];
for (var i = 0; i < matches.length; i++) {
final match = matches.elementAt(i);

if (match.start != lastMatchEnd) {
children.add(TextSpan(
text: source.substring(lastMatchEnd, match.start),
));
}

children.add(TextSpan(
text: source.substring(match.start, match.end),
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
));

if (i == matches.length - 1 && match.end != source.length) {
children.add(TextSpan(
text: source.substring(match.end, source.length),
));
}

lastMatchEnd = match.end;
}
return children;
}

基于您的代码的示例:

RichText(
text: TextSpan(
children: highlightOccurrences(suggestList[index].d, query),
style: TextStyle(color: Colors.grey),
),
),

如果这有帮助,请告诉我。

关于flutter - 如何在 searchDelegate 上突出显示正确的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56558722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com