Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save File in Downloads folder in flutter?

Tags:

flutter

In my flutter application I can create a pdf file, then I want to save it in Download folder. I'm trying to achieve this goal with path_provider package, but I can't.

This is the sample code from flutter's cookbook, If I use it I don't get any error, but I don't find the file either.

final directory = await getApplicationDocumentsDirectory();
File file2 = File("${directory.path}/test.txt");
await file2.writeAsString('TEST ONE');

What's the correct way to do it?

like image 798
Emanuele Vinci Avatar asked Dec 16 '25 13:12

Emanuele Vinci


1 Answers

To find the correct path please use ext_storage. You will need this permission

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

on Android 10 you need this in your manifest

<application
      android:requestLegacyExternalStorage="true"

on Android 11 use this instead

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

Remember to ask for them using permission_handler

I leave you my code:

  static Future saveInStorage(
      String fileName, File file, String extension) async {
    await _checkPermission();
    String _localPath = (await ExtStorage.getExternalStoragePublicDirectory(
        ExtStorage.DIRECTORY_DOWNLOADS))!;
    String filePath =
        _localPath + "/" + fileName.trim() + "_" + Uuid().v4() + extension;

    File fileDef = File(filePath);
    await fileDef.create(recursive: true);
    Uint8List bytes = await file.readAsBytes();
    await fileDef.writeAsBytes(bytes);
  }
like image 126
Emanuele Vinci Avatar answered Dec 19 '25 06:12

Emanuele Vinci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!