register<K, C> static method

EnvironmentInstance<K, C> register<K, C>({
  1. required Map<K, Future<C> Function()> configuration,
  2. required K defaultEnvironment,
  3. EnvResolver<K>? resolver,
  4. @Deprecated('Pass environment: const String.fromEnvironment("YOUR_KEY") instead.') String defineKey = EnvxConstants.defaultDefineKey,
  5. String? environment,
  6. bool cache = false,
  7. bool strict = false,
})

Register an environment.

Generic parameters K and C are typically inferred from configuration and defaultEnvironment; explicit type arguments are only needed for unusual cases.

Parameters:

  • configuration: mapping from environment keys to async configuration builders.
  • defaultEnvironment: key to use when resolution fails.
  • resolver: translation from raw strings to keys. Required for non-string keys. When omitted and the key type is String, an identity resolver is used.
  • environment: a value read at a const call site in the application. When omitted, the fixed APP_ENV const declaration is used.
  • cache: opt-in per-key factory caching, including in-flight requests. Failed futures are evicted and can be retried.
  • strict: rejects unknown or missing environments instead of falling back.
  • defineKey: legacy dynamic key. Custom keys are not portable to AOT; pass environment instead. The default APP_ENV key is reliable.

Implementation

static EnvironmentInstance<K, C> register<K, C>({
  required Map<K, Future<C> Function()> configuration,
  required K defaultEnvironment,
  EnvResolver<K>? resolver,
  @Deprecated(
      'Pass environment: const String.fromEnvironment("YOUR_KEY") instead.')
  String defineKey = EnvxConstants.defaultDefineKey,
  String? environment,
  bool cache = false,
  bool strict = false,
}) {
  var res = resolver;
  if (res == null && K != String) {
    throw ArgumentError('Resolver is required for non-string environments.');
  } else if (res == null && K == String) {
    res = (input) => input as K?;
  }

  final registry = EnvironmentRegistry<K, C>(
    configs: configuration,
    defaultEnvironment: defaultEnvironment,
    cache: cache,
    strict: strict,
  );

  final service = EnvironmentService<K, C>(
    registry: registry,
    resolver: res!,
    defineKey: defineKey,
    environment: environment,
    strict: strict,
  );

  return EnvironmentInstance._(service);
}