withEnvironment<R> function

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

Creates a environment that is contained to the scope of the callback method.

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

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> withEnvironment<R>(Future<R> Function() callback,
    {required Map<String, String> environment}) async {
  final scope = Scope()
    ..value(Env.scopeKey, Env.forScope(environment)..addAll(environment));
  return scope.run(() => callback());
}