Sonnat Project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.3 KiB

  1. import 'package:flutter/material.dart';
  2. class HighlightRichText extends StatelessWidget {
  3. final String text;
  4. final String? highlight;
  5. final TextStyle? style;
  6. final TextStyle? highlightTextStyle;
  7. final TextAlign? textAlign;
  8. const HighlightRichText({
  9. super.key,
  10. required this.text,
  11. this.highlight,
  12. this.style,
  13. this.highlightTextStyle,
  14. this.textAlign,
  15. });
  16. @override
  17. Widget build(BuildContext context) {
  18. if (highlight == null) {
  19. return Text(
  20. text,
  21. style: style,
  22. textAlign: textAlign,
  23. );
  24. }
  25. var split = text.split(RegExp(highlight!, caseSensitive: false));
  26. List<String> withSplit = List.empty(growable: true);
  27. for (int i = 0; i < split.length; i++) {
  28. if (i == split.length - 1) {
  29. withSplit.add(split[i]);
  30. } else {
  31. withSplit.add(split[i]);
  32. withSplit.add(highlight!);
  33. }
  34. }
  35. return RichText(
  36. textAlign: textAlign ?? TextAlign.start,
  37. text: TextSpan(
  38. style: style,
  39. children: withSplit.map((e) {
  40. if (e.toLowerCase().compareTo(highlight!.toLowerCase()) == 0) {
  41. return TextSpan(text: e, style: highlightTextStyle ?? style?.copyWith(backgroundColor: Colors.yellow));
  42. } else {
  43. return TextSpan(text: e);
  44. }
  45. }).toList(),
  46. ),
  47. );
  48. }
  49. }