tryGetRichTextSync function

List<RichTextItem>? tryGetRichTextSync(
  1. String text
)

Parses a rich text string with XML tags and returns a list of RichTextItem.

Supported XML tags (HTML-like):

  • <b> or <bold> or <strong>: Bold text
  • <u> or <underline>: Underlined text
  • <s> or <strike> or <strikethrough> or <del>: Strikethrough text
  • <i> or <italic> or <em>: Italic text
  • <a href="url">: Hyperlink
  • <span> or <font> with attributes:
    • color: Text color (e.g., "#FF0000" or "red")
    • href: Link URL
    • background-color|backgroundColor: Background color
    • font-weight|fontWeight: Font weight (e.g., "700")
    • font-size|fontSize: Font size (e.g., "14")
    • font-family|fontFamily: Font family name
    • font-style|fontStyle: Font style (kItalicFontStyle)
    • text-decoration|textDecoration: Text decoration (kUnderlineTextDecoration, kLineThroughTextDecoration)

Examples:

// Simple bold text
tryGetRichTextSync('hello <b>dart</b>');
// Returns: [RichTextItem(text: 'hello '), RichTextItem(text: 'dart', bold: true)]

// Nested tags
tryGetRichTextSync('hello <b>dart and <u>flutter</u></b>');
// Returns: [
//   RichTextItem(text: 'hello '),
//   RichTextItem(text: 'dart and ', bold: true),
//   RichTextItem(text: 'flutter', bold: true, textDecoration: 'underline')
// ]

Implementation

List<RichTextItem>? tryGetRichTextSync(String text) {
  if (text.isEmpty) {
    return [];
  }

  // Wrap the text in a root element to ensure valid XML
  final wrappedText = '<root>$text</root>';

  XmlDocument document;
  try {
    document = XmlDocument.parse(wrappedText);
  } catch (e) {
    // If parsing fails, return null
    return null;
  }

  final result = <RichTextItem>[];
  final initialStyle = RichTextItem(text: '');

  _parseNode(
    document.rootElement,
    initialStyle,
    RichTextItemDescriptor.empty,
    result,
  );

  return result;
}