exportCsv static method

Future<void> exportCsv(
  1. String fileName,
  2. List<Map<String, dynamic>> rows
)

Exports rows as a CSV file and shares it using shareTextAsFile.

The header row is inferred from the keys of the first row; values are escaped with escape (RFC 4180-style quoting).

Implementation

static Future<void> exportCsv(
  String fileName,
  List<Map<String, dynamic>> rows,
) async {
  if (rows.isEmpty) return;
  final List<String> headers = rows.first.keys.toList();
  final StringBuffer buffer = StringBuffer();
  buffer.writeln(headers.map((String header) => escapeCsvCell(header)).join(','));
  for (final Map<String, dynamic> row in rows) {
    buffer.writeln(
      headers
          .map((String header) => escapeCsvCell((row[header] ?? '').toString()))
          .join(','),
    );
  }
  await FileService.shareTextAsFile(
    fileName: fileName,
    contents: buffer.toString(),
    mimeType: 'text/csv',
  );
}