findWord method
void
findWord(})
Search the document for occurrences of word and add highlight ranges.
word: The substring to search for. If empty, existing highlights are cleared and listeners are notified.highlightStyle: Optional style applied to each found match. If null, a default amber background style is used.matchCase: When true the search is case-sensitive; otherwise the search is performed case-insensitively.matchWholeWord: When true matches are considered valid only when the matched substring is not adjacent to other word characters (letters, digits, or underscore).
Behavior:
Clears existing searchHighlights, scans the document for matches
according to the provided options, appends a SearchHighlight for each
match, sets searchHighlightsChanged = true and calls
notifyListeners() to request a repaint/update.
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();
}