Photo by Chris Ried on Unsplash

Styled Text in flutter

Rex Cole
2 min readJul 29, 2024

We will create a RichText builder in flutter using regex

Widget:

StyledText(text: "This is ([{bold}]) text, [underlined] text, and (italic) text.");

Implementation:


class StyledText extends StatelessWidget {
final String text;
const StyledText({required this.text, super.key});

@override
Widget build(BuildContext context) {
return RichText(
text: TextSpan(
style: const TextStyle(color: Colors.black),
children: _buildTextSpans(text),
),
);
}

List<TextSpan> _buildTextSpans(String text) {
final RegExp pattern = RegExp(r'(\{[^}]+\}|\[[^\]]+\]|\([^)]+\))');
final List<TextSpan> spans = [];
final matches = pattern.allMatches(text);

int lastEnd = 0;
for (final match in matches) {
if (match.start > lastEnd) {
spans.add(TextSpan(text: text.substring(lastEnd, match.start)));
}
final matchedText = match.group(0)!;
final content = matchedText.substring(1, matchedText.length - 1);
spans.add(_applyStyle(matchedText, _buildTextSpans(content)));
lastEnd = match.end;
}
if (lastEnd < text.length) {
spans.add(TextSpan(text: text.substring(lastEnd)));
}
return spans;
}

TextSpan _applyStyle(String text, List<TextSpan> children) {
if (text.startsWith('{')) {
return TextSpan(style: const TextStyle(fontWeight: FontWeight.bold), children: children);
} else if (text.startsWith('[')) {
return TextSpan(style: const TextStyle(decoration: TextDecoration.underline), children: children);
} else if (text.startsWith('(')) {
return TextSpan(style: const TextStyle(fontStyle: FontStyle.italic), children: children);
} else {
return TextSpan(children: children);
}
}
}

Output:

--

--

No responses yet