copyFileIntoDownloadFolder method

  1. @override
Future<File?> copyFileIntoDownloadFolder(
  1. String filePath,
  2. String fileName, {
  3. File? file,
  4. String? desiredExtension,
  5. String? subDirectoryPath,
})
override

Implementation

@override
Future<File?> copyFileIntoDownloadFolder(String filePath, String fileName,
    {File? file, String? desiredExtension, String? subDirectoryPath}) async {
  // Determine the Android SDK version (if it's an Android device).
  final androidSdkVersion =
      Platform.isAndroid ? await getCurrentAndroidSdkVersion() : 0;

  final fileToCopy = file ?? File(filePath);

  // This is a workaround to avoid using MANAGE_EXTERNAL_STORAGE on Android 29 and higher.
  // Instead, we use MediaStore within the native code to save the file.
  if (Platform.isAndroid && androidSdkVersion >= 29) {
    // Use the platform-specific channel to invoke a method and save a file using MediaStore.
    // 'saveFileUsingMediaStore' can only be used with Android API 29 and higher.
    return File((await _saveFileUsingMediaStore(
        fileToCopy,
        basenameWithoutExtension(fileName),
        desiredExtension ?? extension(fileToCopy.path),
        subDirectoryPath: subDirectoryPath))!);
  }
  // Get the path to the download folder.
  final folderPath =
      absolute((await getDownloadFolder()).path, subDirectoryPath);


  // Copy the file to the download folder with the specified file name and ensures a unique name to avoid overwriting existing files
  return fileToCopy.copyTo(folderPath, fileName,
      desiredExtension: desiredExtension ?? extension(fileToCopy.path));
}