我怎樣才能實作這樣的事情。

我想更改下面專案中搜索欄中給定字符的顏色。
uj5u.com熱心網友回復:
要實作這一點取決于資料源是什么以及您將如何處理空格。快速解決。
String search;
TextStyle positiveColorStyle = TextStyle(color: Colors.blue),
TextStyle negativeColorStyle = TextStyle(color: Colors.black);
TextSpan searchMatch(String match) {
if (search == null || search == "")
return TextSpan(text: match, style: negativeColorStyle);
var refinedMatch = match.toLowerCase();
var refinedSearch = search.toLowerCase();
if (refinedMatch.contains(refinedSearch)) {
if (refinedMatch.substring(0, refinedSearch.length) == refinedSearch) {
return TextSpan(
style: posRes,
text: match.substring(0, refinedSearch.length),
children: [
searchMatch(
match.substring(
refinedSearch.length,
),
),
],
);
} else if (refinedMatch.length == refinedSearch.length) {
return TextSpan(text: match, style: positiveColorStyle);
} else {
return TextSpan(
style: negativeColorStyle,
text: match.substring(
0,
refinedMatch.indexOf(refinedSearch),
),
children: [
searchMatch(
match.substring(
refinedMatch.indexOf(refinedSearch),
),
),
],
);
}
} else if (!refinedMatch.contains(refinedSearch)) {
return TextSpan(text: match, style: negativeColorStyle);
}
return TextSpan(
text: match.substring(0, refinedMatch.indexOf(refinedSearch)),
style: negativeColorStyle,
children: [
searchMatch(match.substring(refinedMatch.indexOf(refinedSearch)))
],
);
}
然后呼叫該方法并將搜索到的文本作為引數傳遞:
信用:https : //medium.com/@nogadev/highlight-search-results-in-flutter-66f03974ddec
uj5u.com熱心網友回復:
你應該把你的字串分成兩部分。以子串為例
String str = "Dolania Travel"
String firstPart = str.substring(0, 2);
String secondPart = str.substring(2, str.lenght);
并使用 RichText 示例:
RichText(
text: TextSpan(style: TextStyle(color: Colors.black),
children: [
TextSpan(
text: firstPart,
style: TextStyle(color: Colors.blue),
),
TextSpan(
text: secondPart,
),
]
),
uj5u.com熱心網友回復:
我會沿著這些方向嘗試一些東西。我沒有測驗這個,所以可能有一些索引錯誤,但這個總體思路應該可行。
Widget createText(String name) {
final _stringToMatch = controller.text;
if (!name.toLowerCase().contains(_stringToMatch)) {
return Text(name);
}
final _start = name
.toLowerCase()
.indexOf(_stringToMatch); // gives index where match starts
final _end =
_start _stringToMatch.length - 1; // gives index where match ends
final _customText = TextSpan(
text: name.substring(_start, _end),
style: Theme.of(context).textTheme.bodyText1!.copyWith(
color: Colors.red,
));
return RichText(
text: TextSpan(
text: '',
style: DefaultTextStyle.of(context).style,
children: <TextSpan>[
if (_start == 0) _customText,
TextSpan(text: name.substring(0, _start)),
if (_start != 0) _customText,
if (_end != name.length - 1)
TextSpan(text: name.substring(_end, name.length)),
],
),
);
}
names.map((name) {
return createText(name);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/339516.html
標籤:扑
上一篇:Flutter主題資料
下一篇:顫動:GridView未正確顯示
