setKey static method

void setKey(
  1. String envPath,
  2. String key,
  3. String value, {
  4. String? comment,
})

Set or update key to value in the .env file at envPath.

Behaviour:

  • Creates the file if it does not exist.
  • Updates the value in-place when key already exists (preserving its position and all surrounding lines).
  • Appends a new KEY=VALUE line when key is absent.
  • When comment is supplied, a # <comment> line is prepended immediately above the KEY=VALUE line (for new keys) or replaces the existing comment above the key line (for updates).

Values are quoted if they contain spaces, #, ", ', or $.

@param envPath Absolute or relative path to the .env file. @param key Environment variable name (upper-case by convention). @param value Raw value; quoting is applied automatically. @param comment Optional single-line comment text (without # prefix).

Implementation

static void setKey(
  String envPath,
  String key,
  String value, {
  String? comment,
}) {
  // 1. Load existing lines (empty list when file is absent).
  final file = File(envPath);
  final lines = file.existsSync() ? file.readAsLinesSync() : <String>[];

  // 2. Locate the existing key line index (if any).
  final keyPrefix = '$key=';
  final keyIndex = _findKeyIndex(lines, keyPrefix);

  final encoded = _encode(value);
  final keyLine = '$key=$encoded';

  if (keyIndex == -1) {
    // 3a. Key not present: append (with optional comment).
    if (comment != null) {
      lines.add('# $comment');
    }
    lines.add(keyLine);
  } else {
    // 3b. Key present: replace the value in-place. Also handle comment.
    lines[keyIndex] = keyLine;

    if (comment != null) {
      // Replace or insert the comment immediately above the key line.
      if (keyIndex > 0 && lines[keyIndex - 1].startsWith('#')) {
        lines[keyIndex - 1] = '# $comment';
      } else {
        lines.insert(keyIndex, '# $comment');
      }
    }
  }

  // 4. Write back, ensuring a trailing newline.
  _writeLines(file, lines);
}