setNestedValue function

bool setNestedValue(
  1. dynamic data,
  2. String path,
  3. dynamic value
)

Set value in nested structure using dot notation.

Creates intermediate maps/lists as needed. Returns true if successful.

Implementation

bool setNestedValue(dynamic data, String path, dynamic value) {
  if (data == null) return false;
  if (!(data is Map || data is List)) return false;

  final keys = path.split('.');
  if (keys.isEmpty) return false;

  dynamic current = data;

  // Navigate to parent of target
  for (int i = 0; i < keys.length - 1; i++) {
    final key = keys[i];
    final nextKey = keys[i + 1];

    // Handle list index access
    if (current is List) {
      final index = int.tryParse(key);
      if (index == null || index < 0 || index >= current.length) {
        return false;
      }

      // Create intermediate structure if needed
      if (current[index] == null) {
        final isNextKeyNumeric = int.tryParse(nextKey) != null;
        current[index] = isNextKeyNumeric ? [] : <String, dynamic>{};
      }

      current = current[index];
    }
    // Handle map key access
    else if (current is Map) {
      // Create intermediate structure if needed
      if (!current.containsKey(key) || current[key] == null) {
        final isNextKeyNumeric = int.tryParse(nextKey) != null;
        current[key] = isNextKeyNumeric ? [] : <String, dynamic>{};
      }

      current = current[key];
    }
    // Can't navigate further
    else {
      return false;
    }
  }

  // Set the final value
  final lastKey = keys.last;

  if (current is List) {
    final index = int.tryParse(lastKey);
    if (index == null || index < 0 || index >= current.length) {
      return false;
    }
    current[index] = value;
    return true;
  } else if (current is Map) {
    current[lastKey] = value;
    return true;
  }

  return false;
}