Frederik
Frederik

Reputation: 1293

Flutter: getApplicationDocumentsDirectory() returns null

The method getApplicationDocumentsDirectory() is returning null. I can't figure out why....

getApplicationDocumentsDirectory().then((directory) {
  print(_directory);
  _directory = directory;
});

null is printed to the console...

Do I need to register something or ask for permissions?

Upvotes: 2

Views: 5918

Answers (4)

ǝlpoodooɟƃuooʞ
ǝlpoodooɟƃuooʞ

Reputation: 516

if you added the android permission as suggested and it still does not work try adding WidgetsFlutterBinding.ensureInitialized(); as the very first thing in your main function. this fixed it for me.

Upvotes: 1

Sérgio Ildefonso
Sérgio Ildefonso

Reputation: 72

On AndroidManifest.xml, inside the

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="xxx.yyyy.zzz.www">
...
</manifest>

tag, put the following lines to grant permission:

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

Upvotes: 0

Ping Woo
Ping Woo

Reputation: 1773

In my side, I replace getApplicationDocumentsDirectory with getTemporaryDirectory, it works, I guess the first one no error catching!

Upvotes: 0

Rizwan
Rizwan

Reputation: 1664

You need to ask WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permission.

Inside your manifest add like this :

<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>

and also need Runtime Request Permission, by using simple_permissions package. Refer below code:

    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)
      getApplicationDocumentsDirectory().then((directory) {
        print(_directory);
        _directory = directory;
     });
    }

Refer to this tutorial for learning more about using runtime permission in flutter.

Upvotes: 2

Related Questions