'How to solve "OS Error: File exists, errno = 17" in flutter?

I'm trying to download and save a file in the Downlaod directory, but every time I get this error:

I/flutter (21400): FileSystemException: Cannot create file, path = '/storage/emulated/0/Download/contratto.jpg' (OS Error: File exists, errno = 17)

But if I search this file in my storage I don't find it, I don't understand.

In the Manifest I've all the permissions:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I'm using ext_storage package to find the path, but even with path_provider I got the same error. This is my code:

static Future download(String url, String fileName, String extension) async {
    _checkPermission();
    String _localPath = await ExtStorage.getExternalStoragePublicDirectory(
        ExtStorage.DIRECTORY_DOWNLOADS);
    Dio dio = Dio();
    await dio.download(
      url,
      _localPath + "/" + fileName + "." + extension,
    );
}

I'm using Flutter 2.0.6. Any ideas?

EDIT: The download works only the first time I save a file with a certain name, if I delete it and try to download it again I get this error. I've tried also to reinstall the app but I still get the error



Solution 1:[1]

Apparently seems to be a problem with the way Android deletes files: the first time it works, but the next times the error compare, even if I delete manually the file.

My Solution: append a random string to file's name. I know that it's not so elegant, but it works.

 String filePath =
        _localPath + "/" + fileName + Uuid().v4() + "." + extension;

Solution 2:[2]

I found the solution: Since Android 11, API level 30, there is a new storage protection. You need to request the MANAGE_EXTERNAL_STORAGE access.


Solution

Add to AndroidManifest.xml

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

And request Permission to manage external Storage (example with permission_handler)

await Permission.manageExternalStorage.request();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emanuele Vinci
Solution 2 ratloser