backup function

Stream<double> backup(
  1. String to
)

Implementation

Stream<double> backup(String to) async* {
  final encoder = ZipFileEncoder();
  encoder.create(to);

  try {
    // Directory for files to be backed up
    final directory = Directory(await localPath);

    // List all files and directories recursively
    final List<FileSystemEntity> entities = directory.listSync(recursive: true);

    // Calculate the total size of all files for progress tracking
    final int totalSize = entities
        .whereType<File>()
        .fold(0, (sum, file) => sum + file.lengthSync());
    int processedSize = 0;

    // Iterate over each entity
    for (final entity in entities) {
      if (entity is File) {
        // Get the relative path of the file
        final String relativePath =
            entity.path.replaceFirst(directory.path, '');

        // Add file to the ZIP while preserving folder structure
        encoder.addFile(entity, relativePath);

        // Update processed size
        processedSize += entity.lengthSync();

        // Yield progress as a percentage of total size
        yield processedSize / totalSize;
      }
    }
  } finally {
    // Ensure the encoder is closed properly
    encoder.close();
  }
}