Save files from download directory with flutter

Asked

Viewed 533 times

1

I am generating a PDF file and I want to save it in the "downloads" of mobile device, I am using "downloads_path_provider: 0.1.0" for this but when I save I have the following error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FileSystemException: Cannot open file, path = 'Directory: '/storage/emulated/0/Download'/example.pdf' (OS Error: No such file or directory, errno = 2)

the code itself is quite simple because I’m still starting:

teste() async {
//  Directory documentDirectory  = await getApplicationDocumentsDirectory();

//  String documentPath = documentDirectory.path;
 Directory downloadsDirectory;
 final doc = pw.Document();
 try {
   downloadsDirectory = await DownloadsPathProvider.downloadsDirectory;
 } on PlatformException {
   print('Could not get the downloads directory');
 }
 print(downloadsDirectory);
 doc.addPage(
   pw.Page(
     build: (pw.Context context) => pw.Center(
       child: pw.Text('batata'),
     ),
   ),
 );
 File file = File("$downloadsDirectory/example.pdf");

 file.writeAsBytesSync(doc.save());
}

I thought it might be because I use an emulator but I had the same problem on the real device.

1 answer

1


In the error message we can see that:

path = 'Directory: '/Storage/Emulated/0/Download'/example.pdf'

That is, he thinks the path provided by you is

Directory: '/storage/emulated/0/Download'/example.pdf

This is not a valid path (you have this "Directory:" at the beginning and the quotation marks).

This is because you are forming your path string with the Directory class directly. Your method toString() returns a description of the class itself, not just the path.

Try using the property path of the Directory class:

That is, replace the following line:

File file = File("$downloadsDirectory/example.pdf");

for:

File file = File("${downloadsDirectory.path}/example.pdf");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.