findWord method
void
findWord(})
Implementation
void findWord(
String word, {
TextStyle? highlightStyle,
bool matchCase = false,
bool matchWholeWord = false,
}) {
final style =
highlightStyle ?? const TextStyle(backgroundColor: Colors.amberAccent);
searchHighlights.clear();
if (word.isEmpty) {
searchHighlightsChanged = true;
notifyListeners();
return;
}
final searchText = text;
final searchWord = matchCase ? word : word.toLowerCase();
final textToSearch = matchCase ? searchText : searchText.toLowerCase();
int offset = 0;
while (offset < textToSearch.length) {
final index = textToSearch.indexOf(searchWord, offset);
if (index == -1) break;
bool isMatch = true;
if (matchWholeWord) {
final before = index > 0 ? searchText[index - 1] : '';
final after = index + word.length < searchText.length
? searchText[index + word.length]
: '';
final isWordChar = RegExp(r'\w');
final beforeIsWord = before.isNotEmpty && isWordChar.hasMatch(before);
final afterIsWord = after.isNotEmpty && isWordChar.hasMatch(after);
if (beforeIsWord || afterIsWord) {
isMatch = false;
}
}
if (isMatch) {
searchHighlights.add(
SearchHighlight(start: index, end: index + word.length, style: style),
);
}
offset = index + 1;
}
searchHighlightsChanged = true;
notifyListeners();
}