substring_highlight
以字符级别高亮 Flutter 文本。专为不区分大小写的搜索词高亮设计,单个搜索词子字符串(可能多次)在一个更长的字符串中被高亮。受现有 Flutter 包“highlight_text”启发,但支持子词字符匹配(例如,“Peter”中的“t”)。限制:仅支持单个搜索词,不支持可点击的高亮子字符串。
正在搜索高亮显示的子字符串不必匹配更长字符串的开头(可以位于任何位置,不区分大小写)。
即使是空格字符也会匹配,但本身不会被高亮。
祖先必须设置 {textDirection},通过 {MaterialApp widget} 或显式包装 {Directionality} widget 设置
Directionality(child: SubstringHighlight(text: 'Peter', term: 't'), textDirection: TextDirection.ltr)
默认样式示例
代码
例如,以下代码片段使用此包高亮显示每个搜索结果中的匹配字符
import 'package:substring_highlight/substring_highlight.dart';
...
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(12),
child: SubstringHighlight(
text: dropDownItem, // search result string from database or something
term: searchTerm, // user typed "et"
),
);
}
输出

自定义样式示例
代码
此示例添加了“textStyle”和“textStyleHighlight”以更改文本颜色
import 'package:substring_highlight/substring_highlight.dart';
...
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(12),
child: SubstringHighlight(
text: dropDownItem, // each string needing highlighting
term: searchTerm, // user typed "m4a"
textStyle: TextStyle( // non-highlight style
color: Colors.grey,
),
textStyleHighlight: TextStyle( // highlight style
color: Colors.black,
decoration: TextDecoration.underline,
),
),
);
}
输出
