Your query ‘THIS IS TESTING SUBJECT TRYING TO EXPLORE HAHA .’ has been raised with ticket id: #0606c2a23d9e
I want to make like this
How to make it like this
2
you can use RichText widget for this purpose in which you can give different styling to different part of the text
RichText( text: TextSpan( text: 'Hello ', style: DefaultTextStyle.of(context).style, children: const <TextSpan>[ TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)), TextSpan(text: ' world!'), ], ), )
Let’s assume that we have a pattern with single quotes
Your query 'THIS IS TESTING SUBJECT TRYING TO EXPLORE HAHA .' has been raised with ticket id: #0606c2a23d9e
Let’s split your task into subtasks:
First, specify the regex
regex
final regex = RegExp(''.+'');
Next, let’s try to find our target value with regex (assume that we have it all the time to omit nullability case here)
target
final target = regex.stringMatch(string)!;
Next, replace the target in the original string with some placeholder
placeholder
final placeholder = '{@}'; final updatedString = string.replaceAll(regex, placeholder);
Next, split updatedString into tokens
updatedString
tokens
final tokens = updatedString.split(RegExp(' '));
Next, build our TextSpan‘s by tokens. If the token is a placeholder then we replace it with the target and needed style
TextSpan
token
final spans = tokens .map((e) => e == placeholder ? TextSpan(text: target + ' ', style: TextStyle(color: Colors.blue)) : TextSpan(text: e + ' ')) .toList();
And last, collect everything together
Text.rich(TextSpan(children: spans)))
Full code example
class Page extends StatelessWidget { final String string; const Page({Key? key, required this.string}) : super(key: key); @override Widget build(BuildContext context) { final regex = RegExp(''.+''); const placeholder = '{@}'; final target = regex.stringMatch(string)!; final updatedString = string.replaceAll(regex, placeholder); final tokens = updatedString.split(RegExp(' ')); final spans = tokens .map((e) => e == placeholder ? TextSpan(text: target + ' ', style: const TextStyle(color: Colors.blue)) : TextSpan(text: e + ' ')) .toList(); return Center(child: Text.rich(TextSpan(children: spans))); } }
Click here to cancel reply.
2
Answers
you can use RichText widget for this purpose in which you can give different styling to different part of the text
Let’s assume that we have a pattern with single quotes
Let’s split your task into subtasks:
First, specify the
regex
Next, let’s try to find our
target
value withregex
(assume that we have it all the time to omit nullability case here)Next, replace the
target
in the original string with someplaceholder
Next, split
updatedString
intotokens
Next, build our
TextSpan
‘s by tokens. If thetoken
is aplaceholder
then we replace it with thetarget
and needed styleAnd last, collect everything together
Full code example