toXmlString method

String toXmlString({
  1. int indent = 0,
  2. required int boundsPrecision,
})

Implementation

String toXmlString({int indent = 0, required int boundsPrecision}) {
  final indentStr = '  ' * indent;
  final tag = widget.runtimeType
      .toString()
      .replaceAll('<', '-')
      .replaceAll('>', '')
      .replaceAll(',', '-')
      .replaceAll(' ', '');

  // associate properties with their values
  Map<String, dynamic> props = {
    for (var p in widget.toDiagnosticsNode().getProperties())
      if (p.name != null && p.value != null)
        p.name!: p.value
            .toString()
            .replaceAll('"', "'")
            .replaceAll("&", "&amp;")
            .replaceAll(RegExp(r'\s+'), ' ')
            .trim(),
  };
  final attrs = [
    ...props.entries.map((e) {
      // Height and line height are conflicting properties
      if (e.key == "height") {
        return ' lineHeight="${e.value}"';
      }
      return ' ${e.key}="${e.value}"';
    }),
    if (bounds != null) ...[
      if (!props.containsKey("left"))
        ' left="${bounds!.left.toStringAsFixed(boundsPrecision)}"',
      if (!props.containsKey("top"))
        ' top="${bounds!.top.toStringAsFixed(boundsPrecision)}"',
      ' width="${bounds!.width.toStringAsFixed(boundsPrecision)}"',
      ' height="${bounds!.height.toStringAsFixed(boundsPrecision)}"',
    ],
    if (constraints is BoxConstraints) ...[
      ' maxHeight="${(constraints as BoxConstraints).maxHeight}"',
      ' maxWidth="${(constraints as BoxConstraints).maxWidth}"',
      ' minHeight="${(constraints as BoxConstraints).minHeight}"',
      ' minWidth="${(constraints as BoxConstraints).minWidth}"',
    ],
    if (widget is RichText) ...[
      ' color="${(widget as RichText).text.style?.color?.toString() ?? 'null'}"',
      ' family="${(widget as RichText).text.style?.fontFamily ?? 'null'}"',
      ' size="${(widget as RichText).text.style?.fontSize ?? 'null'}"',
      ' weight="${(widget as RichText).text.style?.fontWeight?.toString() ?? 'null'}"',
      ' lineHeight="${(widget as RichText).text.style?.height?.toString() ?? 'null'}"',
    ],
  ].join('');

  final content = children.isEmpty
      ? ''
      : [
            '',
            ...children.map((child) => child.toXmlString(
                indent: indent + 1, boundsPrecision: boundsPrecision)),
            '',
          ].join('\n') +
          indentStr;
  final slash = children.isEmpty ? ' /' : '';
  final closingTag = children.isEmpty ? '' : '</$tag>';
  final result = '$indentStr<$tag$attrs$slash>$content$closingTag'
      // replace UID hash codes with a generic placeholder
      .replaceAllMapped(RegExp(r'([a-zA-Z_>]+)#[0-9a-fA-F]+'),
          (match) => '${match.group(1)}#HASH');
  return result;
}