Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter : Create directory on external storage path - path provider getExternalStorageDirectory()

I'm creating a flutter app where I want to download and store an image to the external storage (not documents directory) so it can be viewed by any photo gallery app. I'm using the following code to create a directory

var dir = await getExternalStorageDirectory();
  if(!Directory("${dir.path}/myapp").existsSync()){
    Directory("${dir.path}/myapp").createSync(recursive: true);
  }

It's giving me following error:

FileSystemException: Creation failed, path = '/storage/emulated/0/myapp' (OS Error: Permission denied, errno = 13)

I have set up permissions in the manifest file and using the following code for runtime permissions

List<Permissions> permissions = await Permission.getPermissionStatus([PermissionName.Storage]);
permissions.forEach((p) async {
  if(p.permissionStatus != PermissionStatus.allow){
    final res = await Permission.requestSinglePermission(PermissionName.Storage);
    print(res);
  }
});

I have verified in settings that app has got the permission, also as suggested on some answers here I've also tried giving permission from settings app manually which did not work.

like image 467
Gaurav Pingale Avatar asked Jan 26 '19 14:01

Gaurav Pingale


People also ask

How do you get the storage path in flutter?

When using Flutter Official path_provider package, getExternalStorageDirectory() will always return path to /storage/emulated/0/your-package-name/files. The plugin ext_storage uses a deprecated version of the Android embedding.


1 Answers

You need to request permissions before saving a file using getExternalStorageDirectory.

Add this to Androidmanifest.xml:

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

Then use the permission_handler package to get Storage permission:

https://pub.dev/packages/permission_handler

If you are running in the Emulator, getExternalStorageDirectory returns:

/storage/emulated/0/Android/data/com.example.myapp/files/

If you just need the external dir to create a directory under it, then just use:

/storage/emulated/0/

You can create a directory under this folder, so they user will be able to open the files.

like image 135
live-love Avatar answered Oct 09 '22 14:10

live-love