Advertisement
antasofa

Colored Text Search

Jun 18th, 2024
661
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 0.99 KB | Source Code | 0 0
  1.  
  2. Widget coloredSearchText(BuildContext context,
  3.     {String? searchKey, required String searchText, TextStyle? style}) {
  4.   final search = searchKey?.toLowerCase();
  5.   final text = searchText;
  6.  
  7.   final textSpans = <TextSpan>[];
  8.  
  9.   var lastEnd = 0;
  10.   for (final match in (search ?? '').allMatches(text.toLowerCase())) {
  11.     if (match.start > lastEnd) {
  12.       textSpans.add(
  13.         TextSpan(
  14.           text: text.substring(lastEnd, match.start),
  15.           style: style ?? DefaultTextStyle.of(context).style,
  16.         ),
  17.       );
  18.     }
  19.     textSpans.add(
  20.       TextSpan(
  21.         text: text.substring(match.start, match.end),
  22.         style: style?.copyWith(color: context.primaryColor),
  23.       ),
  24.     );
  25.     lastEnd = match.end;
  26.   }
  27.   if (lastEnd < text.length) {
  28.     textSpans.add(
  29.       TextSpan(
  30.         text: text.substring(lastEnd),
  31.         style: style ?? DefaultTextStyle.of(context).style,
  32.       ),
  33.     );
  34.   }
  35.  
  36.   return Text.rich(TextSpan(children: textSpans, style: style));
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement