update static method
dynamic
update(
- Map? json,
- String path,
- dynamic newValue
)
Implementation
static dynamic update(Map<dynamic, dynamic>? json, String path, dynamic newValue) {
json ??= {};
if (path.isEmpty) return newValue;
final parts = path.split('.');
if (parts.isEmpty) return newValue;
final key = parts.first;
final restPath = parts.sublist(1).join('.');
// Try to parse key as int for List index access
final index = int.tryParse(key);
// Handle Map case (or create a Map if input is null)
if (index == null) {
final updated = Map<dynamic, dynamic>.from(json);
if (restPath.isEmpty) {
updated[key] = newValue;
return updated;
}
updated[key] = update(updated.containsKey(key) ? updated[key] : null, restPath, newValue);
return updated;
}
// Handle List case (or create a List if input is null)
else if (index >= 0) {
final list = List<dynamic>.from(json.values);
// Expand list if necessary
while (list.length <= index) {
list.add(null);
}
if (restPath.isEmpty) {
list[index] = newValue;
return list;
}
list[index] = update(list[index], restPath, newValue);
return list;
}
// If path is at leaf but input is neither Map nor List, try to create Map or List if possible
else if (restPath.isEmpty) {
if (index >= 0) {
// key is int -> create a list with newValue at index
final list = List.filled(index + 1, null, growable: true);
list[index] = newValue;
return list;
}
}
// Invalid path, return input unchanged
return json;
}