buildNoTapHighlight static method

Widget buildNoTapHighlight({
  1. required String text,
  2. String highlightText = "",
  3. required TextStyle textStyle,
  4. required TextStyle highlightStyle,
  5. int maxLines = 1,
  6. TextOverflow overflow = TextOverflow.ellipsis,
})

Implementation

static Widget buildNoTapHighlight({
  required String text,
  String highlightText = "",
  required TextStyle textStyle,
  required TextStyle highlightStyle,
  int maxLines = 1,
  TextOverflow overflow = TextOverflow.ellipsis,
}) {
  if (highlightText.isEmpty) {
    return Text(text, maxLines: maxLines, overflow: overflow, style: textStyle);
  }

  final lowercaseText = text.toLowerCase();
  final lowercaseHighlight = highlightText.toLowerCase();
  List<TextSpan> spans = [];
  int currentIndex = 0;

  while (currentIndex < text.length) {
    int highlightIndex = lowercaseText.indexOf(lowercaseHighlight, currentIndex);
    if (highlightIndex == -1) {
      spans.add(TextSpan(text: text.substring(currentIndex), style: textStyle));
      break;
    }

    if (highlightIndex > currentIndex) {
      spans.add(TextSpan(text: text.substring(currentIndex, highlightIndex), style: textStyle));
    }

    spans.add(TextSpan(
      text: text.substring(highlightIndex, highlightIndex + highlightText.length),
      style: highlightStyle,
    ));

    currentIndex = highlightIndex + highlightText.length;
  }

  return RichText(
    maxLines: maxLines,
    overflow: overflow,
    text: TextSpan(children: spans),
  );
}