toStringPretty function Null safety

String toStringPretty(
  1. Object object,
  2. [Map<String, Object>? values]
)

Stringfy any object pretty.

Example:

class Inner {
  Inner();
  final three = 'clap!';

  @override
  String toString() => toStringPretty(this, {
      'three': three,
    });
}

class Outer {
  Outer();
  final one = 1;
  final two = 2;
  final three = Inner();

  @override
  String toString() => toStringPretty(this, {
      'one': one,
      'two': two,
      'three': three,
    });
}

void main() {
  print(Outer());
}

Console:

Outer {
   one: 1
   two: 2
   three: Inner {
       three: clap!
   },
},

Implementation

String toStringPretty(Object object, [Map<String, Object>? values]) {
  if (object is Iterable) return _toPrettyIterable(object);
  if (object is Map) return _toPrettyMap(object);
  if (object is Set) return _toPrettySet(object);

  final buf = StringBuffer();

  if (object is String) {
    if (object.isEmpty) {
      buf.writeln('{');
    } else {
      buf.writeln('$object {');
    }
  } else {
    buf.writeln('${object.runtimeType} {');
  }
  values?.forEach((key, value) {
    buf.writeAll(_shiftln(value, key));
  });
  buf.write('},');

  return buf.toString();
}