set static method

Map set(
  1. Map map,
  2. String key,
  3. dynamic value
)

Sets value at key in map, creating nested maps along the path. Mutates map in place and returns it for chaining.

Existing Lists encountered along the path are traversed by integer segment (e.g. 'users.0.name'); Lists are not auto-created. Existing non-collection intermediates (e.g. an int or String) are left in place and the call becomes a no-op so that data isn't silently destroyed.

Implementation

static Map set(Map map, String key, dynamic value) {
  if (key.isEmpty) return map;
  final List<String> segments = key.split('.');
  dynamic current = map;
  for (var i = 0; i < segments.length - 1; i++) {
    final String s = segments[i];
    if (current is Map) {
      final dynamic next = current[s];
      if (next is Map || next is List) {
        current = next;
      } else if (next == null) {
        final fresh = <String, dynamic>{};
        current[s] = fresh;
        current = fresh;
      } else {
        return map;
      }
    } else if (current is List) {
      final int? idx = int.tryParse(s);
      if (idx == null || idx < 0 || idx >= current.length) return map;
      current = current[idx];
    } else {
      return map;
    }
  }
  final String last = segments.last;
  if (current is Map) {
    current[last] = value;
  } else if (current is List) {
    final int? idx = int.tryParse(last);
    if (idx != null && idx >= 0 && idx < current.length) {
      current[idx] = value;
    }
  }
  return map;
}