withEnvironmentAsync<R> function

Future<R> withEnvironmentAsync<R>(
  1. Future<R> callback(), {
  2. required Map<String, String> environment,
})

Injects environment variables into the scope of the callback method.

The passed environment map is merged with the current env and injected into the callback's scope.

Note: code that access Platform.environment directly will not see the environment variables injected via this method. You must use the dcli env variable.

Any changes to env within the scope of the callback are only visible inside that scope and revert once callback returns. This is particularly useful for unit tests and running a process that requires specific environment variables.

Implementation

Future<R> withEnvironmentAsync<R>(Future<R> Function() callback,
    {required Map<String, String> environment}) async {
  final existing = Env()._envVars;
  return (Scope()
        ..value(Env.scopeKey, Env.forScope(existing)..addAll(environment)))
      .run(() async => callback());
}