humanizeKeyValuePairs function

String humanizeKeyValuePairs(
  1. Map<String, dynamic> data, {
  2. String separator = ': ',
  3. bool alignValues = true,
  4. int maxKeyWidth = 0,
})

Formats key-value pairs with proper alignment.

Implementation

String humanizeKeyValuePairs(Map<String, dynamic> data, {
  String separator = ': ',
  bool alignValues = true,
  int maxKeyWidth = 0,
}) {
  if (data.isEmpty) return '';

  final entries = data.entries.toList();
  final keyWidth = alignValues
      ? math.max(maxKeyWidth, entries.map((e) => e.key.length).reduce(math.max))
      : 0;

  final buffer = StringBuffer();
  for (final entry in entries) {
    final key = alignValues ? entry.key.padRight(keyWidth) : entry.key;
    final value = _formatValue(entry.value);
    buffer.writeln('$key$separator$value');
  }

  return buffer.toString().trim();
}