import 'package:flutter/material.dart'; class HighlightTextSearch extends StatelessWidget { final String data; final String? searchText; final bool enable; final TextStyle style; final Color highlightColor; const HighlightTextSearch({ super.key, this.searchText, this.enable = true, required this.data, required this.style, this.highlightColor = Colors.amber, }); @override Widget build(BuildContext context) { if (searchText == null || searchText!.isEmpty && enable == true) { return Text( data, style: style, overflow: TextOverflow.ellipsis, maxLines: 1, ); } final lowerCaseUserName = data.toLowerCase(); final lowerCaseSearchText = searchText!.toLowerCase(); final highlightedSpans = <TextSpan>[]; int start = 0; while (start < lowerCaseUserName.length) { final index = lowerCaseUserName.indexOf(lowerCaseSearchText, start); if (index == -1) { highlightedSpans.add(TextSpan( text: data.substring(start), style: style, )); break; } if (index > start) { highlightedSpans.add(TextSpan( text: data.substring(start, index), style: style, )); } highlightedSpans.add(TextSpan( text: data.substring(index, index + lowerCaseSearchText.length), style: style.copyWith(color: highlightColor), )); start = index + lowerCaseSearchText.length; } return RichText( text: TextSpan( children: highlightedSpans, ), overflow: TextOverflow.ellipsis, maxLines: 1, ); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter