getHighlightSpans function

  1. @visibleForTesting
List<TextSpan> getHighlightSpans({
  1. required String getText(
    1. String
    ),
  2. required String highlight,
  3. required TextStyle highlightStyle,
})

Returns a List of TextSpans that format highlight with highlightStyle This will call getText with highlight to get a String where highlight can be substituted in It will return a List of TextSpan where the first occurrence of highlight has highlightStyle as the applied style If highlight appears in getText but is not the substituted value this will not be counted as the first occurrence Only the first highlight will be styled with highlightStyle

Implementation

@visibleForTesting
List<TextSpan> getHighlightSpans({
  required String Function(String) getText,
  required String highlight,
  required TextStyle highlightStyle,
}) {
  final emptyTitle = getText('');
  final realTitle = getText(highlight);

  if (realTitle.length == emptyTitle.length) {
    return [TextSpan(text: realTitle)];
  } else {
    int startIndex = emptyTitle.length;
    for (int i = 0; i < emptyTitle.length; i++) {
      if (realTitle[i] != emptyTitle[i]) {
        startIndex = i;
        break;
      }
    }
    return [
      if (startIndex != 0) TextSpan(text: realTitle.substring(0, startIndex)),
      TextSpan(text: highlight, style: highlightStyle),
      if (startIndex + highlight.length < realTitle.length)
        TextSpan(text: realTitle.substring(startIndex + highlight.length)),
    ];
  }
}