encode method

String encode(
  1. List<List> data,
  2. CsvConfig config
)

Encode rows to CSV string with type-aware quoting.

With CsvConfig.hasHeader, the first row is treated as the header row: it is written verbatim (no CsvConfig.encoderTransform) and its names are passed to the transform for the data rows.

Implementation

String encode(List<List<dynamic>> data, CsvConfig config) {
  if (data.isEmpty) return config.addBom ? '' : '';

  final buf = StringBuffer();
  if (config.addBom) buf.writeCharCode(0xFEFF);

  final delim = config.fieldDelimiter;
  final lineDelim = config.lineDelimiter;
  final quote = config.quoteCharacter;
  final escape = config.escapeCharacter;
  final mode = config.quoteMode;
  final transform = config.encoderTransform;
  final hasHeader = config.hasHeader;

  List<String>? headerNames;
  if (transform != null && hasHeader) {
    headerNames = data.first
        .map((e) => e?.toString() ?? '')
        .toList(growable: false);
  }

  for (var r = 0; r < data.length; r++) {
    final row = data[r];
    final isHeaderRow = hasHeader && r == 0;
    for (var c = 0; c < row.length; c++) {
      if (c > 0) buf.write(delim);
      var cell = row[c];
      if (transform != null && !isHeaderRow) {
        final hdr = (headerNames != null && c < headerNames.length)
            ? headerNames[c]
            : null;
        cell = transform(cell, c, hdr);
      }
      writeCell(buf, cell, delim, quote, escape, mode);
    }
    if (r < data.length - 1) buf.write(lineDelim);
  }

  return buf.toString();
}