saveFileToDirectory static method

Future<String?> saveFileToDirectory({
  1. required DirectoryLocation directory,
  2. required Uint8List data,
  3. required String fileName,
  4. String? mimeType,
  5. bool replace = false,
  6. Future onFileExists()?,
})

Saves a file to the specified directory that picked by pickDirectory. The file is saving in background, be sure the directory is permission granted. Availabe on Android 21/iOS 13 and above.

mimeType is required for Android. replace iOS only onFileExists iOS only

  • on iOS In case to prevent files from being overwritten unexpectedly, by default: this method will skip saving file if that file already exists. You can provide a callback onFileExists to ask your user and call saveFileToDirectory again. If replace is true, onFileExists will be ignored.

  • on Android: fileName will be renamed automaticlly by Android if file already exists.

Returns path of the saved file. Throws exception on error.

Implementation

static Future<String?> saveFileToDirectory({
  required DirectoryLocation directory,
  required Uint8List data,
  required String fileName,
  String? mimeType,
  bool replace = false,
  Future Function()? onFileExists,
}) async {
  try {
    return await _channel.invokeMethod('saveFileToDirectory', {
      'directory': directory._rawUri,
      'data': data,
      'fileName': fileName,
      'mimeType': mimeType,
      'replace': replace,
    });
  } on PlatformException catch (e) {
    if (e.code == 'file_already_exists') {
      if (onFileExists != null) await onFileExists();
      return null;
    }

    rethrow;
  }
}