copyDirectory method

Future<void> copyDirectory(
  1. String source,
  2. String destination
)

Copy a directory and all its contents to a new location

Implementation

Future<void> copyDirectory(String source, String destination) async {
  final sourceDir = Directory(source);
  if (!await sourceDir.exists()) {
    throw FileSystemException('Source directory not found', source);
  }

  final destDir = Directory(destination);
  await destDir.create(recursive: true);

  await for (final entity in sourceDir.list(recursive: true)) {
    final relativePath = entity.path.substring(sourceDir.path.length + 1);
    final destPath = '$destination${Platform.pathSeparator}$relativePath';

    if (entity is File) {
      await File(destPath).parent.create(recursive: true);
      await entity.copy(destPath);
    } else if (entity is Directory) {
      await Directory(destPath).create(recursive: true);
    }
  }
}