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 DeviceInfoPlugin().androidInfo).version.sdkInt
      : 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 methodChannel.invokeMethod<bool>(
      'saveFileUsingMediaStore',
      {
        'filePath': fileToCopy.path,
        'fileName': basenameWithoutExtension(fileName),
        'extension': desiredExtension ?? extension(file?.path ?? filePath)
      },
    );
  }
  // Get the path to the download folder.
  final folderPath = await getDownloadFolderPath();

  // 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(folderPath!, fileName,
      desiredExtension: desiredExtension);

  return true;
}