generateSVG method

String generateSVG(
  1. QRCodeData data,
  2. QROptions options, {
  3. int size = 256,
  4. String foregroundColor = '#000000',
  5. String backgroundColor = '#FFFFFF',
})

Generate QR code as SVG string

Implementation

String generateSVG(
  QRCodeData data,
  QROptions options, {
  int size = 256,
  String foregroundColor = '#000000',
  String backgroundColor = '#FFFFFF',
}) {
  final payload = _createPayload(data, options);

  // For simplicity, we'll create a basic SVG
  // In production, you might want to use a more sophisticated approach
  final qrCode = QrCode.fromData(
    data: payload,
    errorCorrectLevel: QrErrorCorrectLevel.M,
  );
  final qrImage = QrImage(qrCode);

  final moduleCount = qrCode.moduleCount;
  final moduleSize = size ~/ moduleCount;

  final svg = StringBuffer();
  svg.write('<svg xmlns="http://www.w3.org/2000/svg" ');
  svg.write('width="$size" height="$size" viewBox="0 0 $size $size">\n');
  svg.write('<rect width="100%" height="100%" fill="$backgroundColor"/>\n');
  svg.write('<g fill="$foregroundColor">\n');

  for (int y = 0; y < moduleCount; y++) {
    for (int x = 0; x < moduleCount; x++) {
      if (qrImage.isDark(y, x)) {
        svg.write('<rect x="${x * moduleSize}" y="${y * moduleSize}" ');
        svg.write('width="$moduleSize" height="$moduleSize"/>\n');
      }
    }
  }

  svg.write('</g>\n</svg>');
  return svg.toString();
}