init<E extends Enum> static method

Future<EnvManager<E>> init<E extends Enum>({
  1. required E defaultEnv,
  2. required Map<E, String> configs,
  3. Set<E>? lockedEnvironments,
  4. EnvLoader? loader,
  5. EnvStore? store,
})

Initialises the singleton with defaultEnv and the configs map.

Loads all .env asset files in parallel. If a previously persisted selection exists, it is restored; otherwise defaultEnv is used.

lockedEnvironments is an optional set of environments from which switching is forbidden. When the active environment is in this set, switchTo throws EnvSwitchLockedException. Defaults to no lock.

Throws EnvLoadException when any asset fails to load. Safe to call multiple times (subsequent calls replace the instance).

Implementation

static Future<EnvManager<E>> init<E extends Enum>({
  required E defaultEnv,
  required Map<E, String> configs,
  Set<E>? lockedEnvironments,
  EnvLoader? loader,
  EnvStore? store,
}) async {
  final resolvedLoader = loader ?? EnvLoader();
  final resolvedStore = store ?? EnvStore();

  // Load all env files concurrently.
  final entries = configs.entries.toList();
  final results = await Future.wait(
    entries.map((e) => resolvedLoader.load(e.value)),
  );

  final envs = <E, Map<String, String>>{};
  for (var i = 0; i < entries.length; i++) {
    envs[entries[i].key] = results[i];
  }

  // Attempt to restore a previously persisted selection.
  final savedName = await resolvedStore.load();
  final allEnumValues = configs.keys.toList();
  final restoredEnv = savedName != null
      ? allEnumValues.cast<E?>().firstWhere(
            (e) => e?.name == savedName,
            orElse: () => null,
          )
      : null;

  final manager = EnvManager<E>._(
    defaultEnv: restoredEnv ?? defaultEnv,
    store: resolvedStore,
    envs: envs,
    allEnumValues: allEnumValues,
    lockedEnvironments: lockedEnvironments ?? const {},
  );

  _instance = manager;
  return manager;
}