Trying to delete an audio file but giving exception in flutter

Viewed 80

I'm trying to delete song file but it is unable to delete and throws an exception of permission denied but permissions are already granted using permission_handler and required storage permissions are added in AndroidManifest.xml as well. I have also checked path is valid and file exist before delete which return true. Would anyone help me to solve this.

Error on file.delete() line.

Unhandled Exception: FileSystemException: Deletion failed, path = '/storage/0E15-2E06/Music/Call Sound Effect.mp3' (OS Error: Permission denied, errno = 13)

AndroidManifest:

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

<application
        android:label="Example"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher"
        android:usesCleartextTraffic="true"
        android:requestLegacyExternalStorage="true" >

Code snippet:

       if (await Permission.storage.request().isGranted) {
            // Either the permission was already granted before or the user just granted it.
            // permission was granted
            if (song != null) {
              String? path = song.data;
              File file = File(path);
              bool isExist = await file.exists();
              if (isExist) {
                await file.delete(recursive: true);
              }
            }
          }
1 Answers

You have to use the permission_handler(https://pub.dev/packages/permission_handler) package and have to mention some permissions in the Androidmanifest.xml file.

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

Also, you have to ask Permission of storage before doing storage related operation(In your case deletion of audio file).

final _permissionStatus = await Permission.storage.request();
if(_permissionStatus = PermissionStatus.isGranted){
/// Delete audio file
}else{
  /// Permission Denied.
}
Related