generateIconFile function

String? generateIconFile(
  1. String content,
  2. String className
)

Generates a Dart file defining a CustomPainter class for an SVG icon.

This function parses the SVG content, extracts path elements, and generates a Dart class named <className>IconPainter that extends CustomPainter.

The generated painter will render the icon scaled to the given dimension and colored with the given color.

Returns null if the SVG size data cannot be parsed.

Implementation

String? generateIconFile(String content, String className) {
  final document = XmlDocument.parse(content);

  final sizes = parseSvgSizeData(document.rootElement);

  if (sizes == null) {
    return null;
  }
  final sizeParams = [
    Field(
      (b) =>
          b
            ..name = "area"
            ..type = refer("double")
            ..modifier = FieldModifier.final$
            ..assignment = Code('${sizes.area}'),
    ),
    Field(
      (b) =>
          b
            ..name = "widthOffset"
            ..type = refer("double")
            ..modifier = FieldModifier.final$
            ..assignment = Code('${sizes.widthOffset}'),
    ),
    Field(
      (b) =>
          b
            ..name = "heightOffset"
            ..type = refer("double")
            ..modifier = FieldModifier.final$
            ..assignment = Code('${sizes.heightOffset}'),
    ),
  ];

  final paintingList =
      document.rootElement.children.whereType<XmlElement>().toList();

  final cls = _corePainterClass(
    className: className,
    sizeParams: sizeParams,
    paintMethod: _generatePaintMethod(paintingList),
  );

  final lib = Library(
    (b) =>
        b
          ..directives.addAll([
            Directive.import('package:flutter/rendering.dart'),
            Directive.import('package:path_drawing/path_drawing.dart'),
            Directive.import('dart:math', show: ['sqrt']),
          ])
          ..body.addAll([cls]),
  );
  final emitter = DartEmitter();

  return DartFormatter(
    languageVersion: DartFormatter.latestLanguageVersion,
  ).format('${lib.accept(emitter)}');
}