Flutter - delete directory failed (OS Error: Operation not permitted, errno = 1)

Viewed 1132

I have a flutter app that saves pdf files in a temporary directory then the user can press a button to delete these files, in Android everything works fine but in iOS I get this error:

Unhandled Exception: FileSystemException: Deletion failed, path = '/var/mobile/Containers/Data/Application/75048CC8-24E7-4BA3-B748-5603D4F74F60/Library/Caches' (OS Error: Operation not permitted, errno = 1)

The weird thing is also that if you refresh the app you can see that the files have been deleted so actually it works but gives error and blocks the app.

My code for deleting is this:

CupertinoDialogAction(
    child: Text("Ok"),
    onPressed: () async {
        Directory dir = await getTemporaryDirectory();
        dir.deleteSync(recursive: true);
        dir.create();
        Navigator.pop(context);
        openFinishDialog();
    }
),

Also this error shows only in physical devices and not on simulators.

I used the dart package path_provider 2.0.8

2 Answers

Okay I solved the problem by creating a directory inside the TemporaryDirectory and deleting that instead of the TemporaryDirectory, here's the code for creating:

var tempDir = await getTemporaryDirectory();
var tempDirPath = tempDir.path;
final myAppPath = '$tempDirPath/my_app';
final res = await Directory(myAppPath).create(recursive: true);

and here's the code for deleting:

Directory dir = await getTemporaryDirectory();
Directory myDir = Directory(dir.path + "/my_app");
myDir.deleteSync(recursive: true);
myDir.create();

I hope this is useful for someone else, if somebody has a better way to solve this issue please answer!

Creating a Directory inside the directory is the solution, you can also use getApplicationDocumentsDirectory() instead of getTemporaryDirectory() for android and ios.

Related