withTempDir<R> function

Future<R> withTempDir<R>(
  1. Future<R> action(
    1. String tempDir
    ), {
  2. bool keep = false,
  3. String? pathToTempDir,
})

Creates a temp directory and then calls action. Once action completes the temporary directory will be deleted.

The actions return value R is returned from the withTempDir function.

If you pass keep = true then the temp directory won't be deleted. This can be useful when testing and you need to examine the temp directory.

You can optionally pass in your own tempDir via pathToTempDir. This can be useful when sometimes you need to control the tempDir and sometimes you want it created. If you pass in pathToTempDir it will NOT be deleted regardless of the value of keep.

Implementation

Future<R> withTempDir<R>(Future<R> Function(String tempDir) action,
    {bool keep = false, String? pathToTempDir}) async {
  final dir = pathToTempDir ?? await createTempDir();

  R result;
  try {
    result = await action(dir);
  } finally {
    if (!keep && pathToTempDir == null) {
      await deleteDir(dir);
    }
  }
  return result;
}