Flutter - Save file visible to the user
Asked Answered
M

3

17

In a Flutter project I create a pdf document. I can save the document in the path of the app. But the user has no access to it. Alternatively, how can I save the file to another folder where the user sees it?

import 'package:path_provider/path_provider.dart';
  Future<void> savePdfDocument() async {
    final PdfCreater generatedPdf = PdfCreater(document);
    final List<int> generatedPdfDocument = generatedPdf.buildPdf();

    final String dir = (await getApplicationDocumentsDirectory()).path;
    final String path = '$dir/example.pdf';
    final File file = File(path);
    file.writeAsBytesSync(generatedPdfDocument);
  }
Mopes answered 3/12, 2019 at 9:35 Comment(3)
Since you're saving file in Documents directory, user can see it, he may need to go to android/data/data/your_package_name/ folder, if you want to save the file in root directory, you can simply change the path, but make sure you have access to storage permission in Android.Beginning
@Beginning That aint true, the path from getApplicationDocumentsDirectory() isnt accessible to the user. The name can be misleading, its not the documents folder that you see in your phone's File menuGusset
@Gusset Yes, I knew the document folder ins't the one which is at the root of your SD card directory. I thought it's the android/data/package/files one but turned out it's data/data/package/app_flutter/ which indeed ins't accessible to the user.Beginning
P
12

Use downloads_path_provider, on android it will save the file on Downloads.

for IOS, you need to use getApplicationDocumentsDirectoryfrom path_provider and add permissions on info.plist to make the folder visible to the user:

<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>UIFileSharingEnabled</key>
<true/>
Phantasm answered 7/1, 2020 at 13:57 Comment(2)
8 Jan 2021: This plugin has lots of inconsistencies and should no longer be used. Feel free to fork and tweak it.Masseur
If you can't view your files with path_provider in the files app on iOS, this permission will allow you to view them.Horned
R
2

This works like a charm

String documentsPath = '/storage/emulated/0/Documents/';
if (Platform.isIOS) {
  Directory path = await getApplicationDocumentsDirectory();
  documentsPath = path.path;
}

Also don't forgot to add this to pubspec path_provider: 2.0.1

Rubino answered 8/11, 2021 at 14:44 Comment(0)
M
0

Also, be sure to test on a physical device, iOS emulator won't work.

Mcmillen answered 24/11, 2021 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.