saveAs method

Future<File> saveAs(
  1. String path
)

Saves the file to the specified path and deletes the temporary file.

Attempts a fast rename() (zero-copy move) first. If the destination is on a different filesystem, falls back to copy() + delete().

Throws StateError if the file has already been deleted.

Implementation

Future<File> saveAs(String path) async {
  if (_deleted) throw StateError('Cannot save: file has already been deleted or moved.');

  final dest = File(path);
  if (!await dest.parent.exists()) {
    await dest.parent.create(recursive: true);
  }

  try {
    // Attempt fast move (same filesystem)
    final moved = await File(tempPath).rename(path);
    _deleted = true;

    // Clean up the now-empty temp directory
    final dirVal = tempDir;
    if (dirVal != null) {
      try {
        final dir = Directory(dirVal);
        if (await dir.exists()) {
          await dir.delete(recursive: true);
        }
      } catch (_) {}
    }

    return moved;
  } catch (_) {
    // Fallback to copy if cross-device (EXDEV error)
    final copied = await File(tempPath).copy(path);
    await delete();
    return copied;
  }
}