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
52 lines
1.3 KiB
import 'package:flutter/material.dart';
|
|
|
|
class HighlightRichText extends StatelessWidget {
|
|
final String text;
|
|
final String? highlight;
|
|
final TextStyle? style;
|
|
final TextStyle? highlightTextStyle;
|
|
final TextAlign? textAlign;
|
|
|
|
const HighlightRichText({
|
|
super.key,
|
|
required this.text,
|
|
this.highlight,
|
|
this.style,
|
|
this.highlightTextStyle,
|
|
this.textAlign,
|
|
});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
if (highlight == null) {
|
|
return Text(
|
|
text,
|
|
style: style,
|
|
textAlign: textAlign,
|
|
);
|
|
}
|
|
var split = text.split(RegExp(highlight!, caseSensitive: false));
|
|
List<String> withSplit = List.empty(growable: true);
|
|
for (int i = 0; i < split.length; i++) {
|
|
if (i == split.length - 1) {
|
|
withSplit.add(split[i]);
|
|
} else {
|
|
withSplit.add(split[i]);
|
|
withSplit.add(highlight!);
|
|
}
|
|
}
|
|
return RichText(
|
|
textAlign: textAlign ?? TextAlign.start,
|
|
text: TextSpan(
|
|
style: style,
|
|
children: withSplit.map((e) {
|
|
if (e.toLowerCase().compareTo(highlight!.toLowerCase()) == 0) {
|
|
return TextSpan(text: e, style: highlightTextStyle ?? style?.copyWith(backgroundColor: Colors.yellow));
|
|
} else {
|
|
return TextSpan(text: e);
|
|
}
|
|
}).toList(),
|
|
),
|
|
);
|
|
}
|
|
}
|