toTextSpan static method
Returns a TextSpan object you can directly pass to a RichText widget. In addition to the build context and your HTML content, you can pass a function to this method. You can use the function to handle click events on anchor tags. The function will receive the actual link as its argument.
To apply a default text style which affects all of the content
(unless they are overridden) pass in defaultTextStyle
HTML.toTextSpan(
context,
htmlContent,
defaultTextStyle: TextStyle(color: Colors.grey[700]),
);
To overrides and/or apply custom styles to html tags
pass in overrideStyle
which is a Map of String,TextStyle
where String is the html tag, and TextStyle is the style applied
HTML.toTextSpan(
context,
htmlContent,
overrideStyle: {
'p': TextStyle(color: Colors.red),
'a': TextStyle(decoration: TextDecoration.underline),
//...
//...
},
);
Implementation
static TextSpan toTextSpan(
BuildContext context,
String htmlContent, {
Function(dynamic)? linksCallback,
Map<String, TextStyle>? overrideStyle,
TextStyle? defaultTextStyle,
}) {
// Validating empty content
if (htmlContent.isEmpty) {
return const TextSpan();
}
String content = htmlContent;
// to fix a known issue with when appearing after an ending tag
content = content.replaceAll(' ', ' ').replaceAll(' ', ' ');
// to fix a known issue with non self closing <br> tags
content = content.replaceAll('<br>', '<br />');
final Parser parser = Parser(context, content,
linksCallback: linksCallback,
overrideStyleMap: overrideStyle ?? <String, TextStyle>{},
defaultTextStyle: defaultTextStyle);
List<TextSpan> list = <TextSpan>[];
try {
list = parser.parse();
} catch (error, stackTrace) {
debugPrint('simple_html_css Exception: ${error.toString()}');
debugPrint('simple_html_css Stack Trace: ${stackTrace.toString()}');
}
return TextSpan(text: '', children: list);
}