canonicalString function
Builds a deterministic canonical string for value.
Maps emit their keys sorted by toString(); lists keep their order; strings
are quoted; null, num, and bool are normalized to plain text. Recurses
to the value's nesting depth, so it is not intended for untrusted,
arbitrarily-deep input (deep nesting can exhaust the stack).
Example:
canonicalString(<String, Object?>{'b': 1, 'a': 2}); // {"a":2,"b":1}
Audited: 2026-06-12 11:26 EDT
Implementation
String canonicalString(Object? value) {
if (value == null) {
return 'null';
}
// Quote strings so they can never be confused with literals like null/true.
if (value is String) {
return '"$value"';
}
if (value is bool || value is num) {
return value.toString();
}
if (value is List<Object?>) {
return _canonicalList(value);
}
if (value is Map<Object?, Object?>) {
return _canonicalMap(value);
}
// Fallback for any other type: its own string form, quoted for safety.
return '"$value"';
}