Flutter How to move file

File.rename works only if source file and destination path are on the same file system, otherwise you will get a FileSystemException (OS Error: Cross-device link, errno = 18). Therefore it should be used for moving a file only if you are sure that the source file and the destination path are on the same file system.

For example when trying to move a file under the folder /storage/emulated/0/Android/data/ to a new path under the folder /data/user/0/com.my.app/cache/ will fail to FileSystemException.

Here is a small utility function for moving a file safely:

Future<File> moveFile(File sourceFile, String newPath) async {
  try {
    // prefer using rename as it is probably faster
    return await sourceFile.rename(newPath);
  } on FileSystemException catch (e) {
    // if rename fails, copy the source file and then delete it
    final newFile = await sourceFile.copy(newPath);
    await sourceFile.delete();
    return newFile;
  }
}

await File('/storage/emulated/0/Myfolder').rename('/storage/emulated/0/Urfolder')

If the files are on different file systems you need to create a new destination file, read the source file and write the content into the destination file, then delete the source file.