writeTable method

void writeTable(
  1. List models, {
  2. required List<String> headers,
  3. required List<List<String>> rows,
  4. String emptyMessage = 'Nothing to show.',
})

Emits models as JSON when --json is set, otherwise renders rows as an aligned table.

Every list command goes through here, so --json behaves identically across the CLI and a script never has to parse the human format.

Implementation

void writeTable(
  List<dynamic> models, {
  required List<String> headers,
  required List<List<String>> rows,
  String emptyMessage = 'Nothing to show.',
}) {
  if (jsonOutput) {
    writeJson([for (final model in models) (model as dynamic).toJson()]);
    return;
  }
  if (rows.isEmpty) {
    info(emptyMessage);
    return;
  }

  final widths = List<int>.generate(headers.length, (i) => headers[i].length);
  for (final row in rows) {
    for (var i = 0; i < row.length && i < widths.length; i++) {
      if (row[i].length > widths[i]) widths[i] = row[i].length;
    }
  }

  String render(List<String> cells) => [
    for (var i = 0; i < cells.length; i++)
      i == cells.length - 1 ? cells[i] : cells[i].padRight(widths[i]),
  ].join('  ');

  out.writeln(render(headers));
  out.writeln([for (final width in widths) '-' * width].join('  '));
  for (final row in rows) {
    out.writeln(render(row));
  }
}