parseEnvFile static method

Map<String, String> parseEnvFile(
  1. String content
)

Parses .env file content into a Map<String, String>. Handles:

  • Comments (lines starting with #)
  • Empty lines
  • Quoted values (single or double)
  • KEY=VALUE format

Implementation

static Map<String, String> parseEnvFile(String content) {
  final result = <String, String>{};
  for (final line in content.split('\n')) {
    final trimmed = line.trim();
    if (trimmed.isEmpty || trimmed.startsWith('#')) continue;
    final eqIdx = trimmed.indexOf('=');
    if (eqIdx <= 0) continue;
    final key = trimmed.substring(0, eqIdx).trim();
    var value = trimmed.substring(eqIdx + 1).trim();
    // Strip surrounding quotes
    if ((value.startsWith('"') && value.endsWith('"')) ||
        (value.startsWith("'") && value.endsWith("'"))) {
      value = value.substring(1, value.length - 1);
    }
    if (key.isNotEmpty) {
      result[key] = value;
    }
  }
  return result;
}