unflattenKeys method
Unflattens dot-separated keys into nested maps. Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
Map<String, dynamic> unflattenKeys() {
final Map<String, dynamic> out = <String, dynamic>{};
for (final MapEntry<String, dynamic> e in entries) {
final List<String> parts = e.key.split('.');
Map<String, dynamic> parentMap = out;
// Walk every part except the last, creating intermediate maps on demand.
bool descended = true;
for (int i = 0; i < parts.length - 1; i++) {
final String part = parts[i];
final childMap = parentMap.putIfAbsent(part, () => <String, dynamic>{});
if (childMap is Map<String, dynamic>) {
parentMap = childMap;
} else {
// A leaf already sits where a branch is needed (e.g. both "a" and
// "a.b" present). Keep the existing value and SKIP this entry — the
// old code fell through and wrote the leaf into the wrong (outer) map.
descended = false;
break;
}
}
final lastPart = parts.lastOrNull;
if (descended && lastPart != null) parentMap[lastPart] = e.value;
}
return out;
}