copyFileIntoDownloadFolder method

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

Implementation

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

  if (Platform.isAndroid && androidSdkVersion < 29 || Platform.isIOS) {
    final bool status = await Permission.storage.isGranted;
    if (!status) await Permission.storage.request();
    if (!await Permission.storage.isGranted) {
      return false;
    }
  }

  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 _saveFileUsingMediaStore(
        fileToCopy,
        basenameWithoutExtension(fileName),
        desiredExtension ?? extension(fileToCopy.path));
  }
  // Get the path to the download folder.
  final folder = await getDownloadFolder();

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

  return true;
}