trimDeep function
Trims all strings in the value, in nested maps and lists too. Returns the value itself when there is nothing to trim, and a trimmed copy otherwise: the value is never changed.
Implementation
Object? trimDeep(Object? value) {
if (value is String) return value.trim();
if (value is Map<Object?, Object?>) {
Map<Object?, Object?>? copy;
value.forEach((key, item) {
final trimmed = trimDeep(item);
if (!identical(trimmed, item)) (copy ??= Map.of(value))[key] = trimmed;
});
return copy ?? value;
}
if (value is List<Object?>) {
List<Object?>? copy;
for (var i = 0; i < value.length; i++) {
final item = value[i];
final trimmed = trimDeep(item);
if (!identical(trimmed, item)) (copy ??= List.of(value))[i] = trimmed;
}
return copy ?? value;
}
return value;
}