Getting permission to the external storage (file_provider plugin)
please use package permission_handler to request permission.
https://pub.dev/packages/permission_handler
https://github.com/BaseflowIT/flutter-permission-handler
import 'package:permission_handler/permission_handler.dart';
...
void _showFilesinDir({Directory dir}) {
dir.list(recursive: false, followLinks: false)
.listen((FileSystemEntity entity) {
print(entity.path);
});
}
...
onTap: () async{
Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([PermissionGroup.storage]);
var systemTempDir = Directory.systemTemp;
_showFilesinDir(dir: systemTempDir);
final myDir = new Directory('/sdcard');
myDir.exists().then((isThere) {
isThere ? _showFilesinDir(dir: myDir) : print('non-existent');
});
}
...
and the result of emulator look like this:
I/flutter (19980): /data/user/0/xxx.login_challenge/code_cache/flutter_engine <br>
I/flutter (19980): /data/user/0/xxx.login_challenge/code_cache/login_challengeMSBLSX <br>
...
I/flutter (19980): /sdcard/Android <br>
For Android 6.0 and higher, if the app has features that need Dangerous permission (list of dangerous permissions), it has to ask the permission(s) explicitly (look at the images here)
You added the permission to Manifest file, this is not enough, you also need to implement Runtime requests for your permissions also.
I checked on the Flutter repository, it seems they are working on a plugin for this. Here is their discussion.
In Android Q, this Error will be resolved by adding the Following Lines in AndroidManifest file:
<application
android:requestLegacyExternalStorage="true"
Beside needing to add WRITE_EXTERNAL_STORAGE
and READ_EXTERNAL_STORAGE
to your android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xxx.yyy">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
...
</manifest>
You also need Runtime Request Permission, by using simple_permissions package:
import 'package:simple_permissions/simple_permissions.dart';
PermissionStatus permissionResult = await SimplePermissions.requestPermission(Permission. WriteExternalStorage);
if (permissionResult == PermissionStatus.authorized){
// code of read or write file in external storage (SD card)
}
Note:
- when running
SimplePermissions.requestPermission
for the First Time, app will popup a window, you MUST clickALLOW
:
to give permission.
- If you already clicked
DENY
, then uninstall debug app and re-debug it to install and fix this -> trigger the popup window and give you chance to clickALLOW
.