copyFiles static method
Copies files from source directory to target directory with optional filtering.
This method recursively copies files from the source directory to the target directory. It can filter files by file type and supports different build modes.
Parameters:
source- The source directory path to copy fromtarget- The target directory path to copy tofileType- List of file extensions to filter by (without dots, e.g.,['apk', 'aab'])mode- Build mode filter (defaults to "release")
Returns the path of the first copied file.
Throws an Exception if:
- No files are found in the source directory
- No files match the specified file type filter
Implementation
static Future<String?> copyFiles(
String source,
String target, {
List<String> fileType = const [],
String mode = "release",
}) async {
final sourceDir = Directory(source);
final files = await sourceDir.list().toList();
final targetDir = Directory(target);
if (!targetDir.existsSync()) {
await targetDir.create(recursive: true);
}
final output = <String>[];
if (files.isEmpty) {
throw Exception("No files found in ${sourceDir.path}");
}
for (var item in files) {
if (item is Directory) {
final copiedFiles = await copyFiles(
item.path,
target,
fileType: fileType,
);
if (copiedFiles != null) output.add(copiedFiles);
} else {
if (fileType.isEmpty) {
if (item is File) {
final fileName = path.basename(item.path);
final targetPath = path.join(target, fileName);
output.add(targetPath);
if (File(targetPath).existsSync()) {
await File(targetPath).delete();
}
await item.copy(targetPath);
}
} else if (item is File &&
fileType.contains(path.extension(item.path).substring(1))) {
final fileName = path.basename(item.path);
final targetPath = path.join(target, fileName);
output.add(targetPath);
if (File(targetPath).existsSync()) {
await File(targetPath).delete();
}
await item.copy(targetPath);
}
}
}
if (output.isEmpty) {
throw Exception(
"Does not contain any files with the specified type: $fileType",
);
}
return output.first;
}