copyFile method

Future<void> copyFile(
  1. String sourcePath,
  2. String destinationPath, {
  3. void onProgress(
    1. int transferred,
    2. int total
    )?,
})

Copy file with progress callback

Implementation

Future<void> copyFile(String sourcePath, String destinationPath, {
  void Function(int transferred, int total)? onProgress,
}) async {
  final sourceFile = File(sourcePath);
  final destinationFile = File(destinationPath);

  if (!sourceFile.existsSync()) {
    throw FileSystemException('Source file does not exist', sourcePath);
  }

  final sourceLength = await sourceFile.length();
  final sourceStream = sourceFile.openRead();
  final destinationSink = destinationFile.openWrite();

  var transferred = 0;

  await for (final chunk in sourceStream) {
    destinationSink.add(chunk);
    transferred += chunk.length;
    onProgress?.call(transferred, sourceLength);
  }

  await destinationSink.close();
}