Search code examples
flutterfile

In flutter can't access to Download folder


I use the following to get the Download folder:


  Future<String> getDownloadsPath() async {
    final directory = await getExternalStorageDirectory();
    if (directory == null) {
      throw Exception('External storage not found');
    }
    final downloadsDirectory = Directory('${directory.path}/Download');
    if (!await downloadsDirectory.exists()) {
      await downloadsDirectory.create(recursive: true);
    }
    return downloadsDirectory.path;
  }

But the folder I get is: "/storage/emulated/0/Android/data/com.XXX.YYY/files/Download" (instead of what I was expecting: "/storage/emulated/0/Download").

Saving "settings.json" json file to this folder works but when I try to pick it with FilePicker, I don't see it. Here is how I do:

  final path = await getDownloadsPath();

  final result = await FilePicker.platform.pickFiles(
    type: Platform.isAndroid ? FileType.any : FileType.custom,
    allowedExtensions: Platform.isAndroid ? null : ['json'],
    initialDirectory: path,
  );

What's the right way to do that?


Solution

  • Try this:

    
      Future<String?> getDownloadPath() async {
        Directory? directory;
        try {
          if (Platform.isIOS) {
            directory = await getApplicationDocumentsDirectory();
          } else {
            directory = Directory('/storage/emulated/0/Download');
    
            if (!await directory.exists()) {
              directory = await getExternalStorageDirectory();
            }
          }
        } catch (err, stack) {
          print("Error: $err");
        }
        return directory?.path;
      }
    

    Output (Android): /storage/emulated/0/Download