Flutter path_provider error on Android, while on iOS works perfectly

2,777

Solution 1

I've found the bug. The problem was that the fileName was written in non-English letters. Seems like the package reads English-only chars on Android. I've changed it to a static String and it seems to work fine

Solution 2

When working with the filesystem, a safe cross-platform solution involves the usage of path_provider (as you're doing) and path.

import 'package:path/path.dart' as p;

After you've imported it, you can safely "chain" paths using join so your code would become:

final name = p.join(dir.path, filename + ".pdf");
final file = File(name);

Basically join decides how to properly create paths to files on the underlying OS and you should rely on it rather than manually writing slashes. Also, make sure that you have permissions for writing and reading on the manifest file.

Share:
2,777
F.SO7
Author by

F.SO7

Updated on December 21, 2022

Comments

  • F.SO7
    F.SO7 over 1 year

    I'm using the [flutter_pdfview][1] package in my Flutter app, in order to present PDF files downloaded from the internet. I use the path_provider package to download the file and store it in the devicee.

    Both packages works perfectly fine when running the app on iOS, but when I run it on Android (inside Android emulator in VSCode) it seems the path_provider isn't able to load the file.

    In the console I get this error message:

    [onError, {error: java.io.FileNotFoundException: No content provider: thisIsMyFilePath}]

    I am downloading and saving the file like this:

    Future<File> getFileFromUrl(String url, {name}) async {
        var fileName;
    
        if (name != null) {
          fileName = name;
        }
    
        try {
          var data = await http.get(url);
          var bytes = data.bodyBytes;
          var dir = await getApplicationDocumentsDirectory();
          File file = File("${dir.path}/" + fileName + ".pdf");
          print(dir.path);
          File urlFile = await file.writeAsBytes(bytes);
          return urlFile;
        } catch (e) {
          throw Exception("Error opening url file");
        }
    }
    

    Anyone has an idea what can be the Android-only error here? Maybe I need to add something to the manifest I am not aware of?

    Thank you very much! [1]: https://pub.dev/packages/flutter_pdfview

    Edit: Alberto Miola answer

    var data = await http.get(url);
          var bytes = data.bodyBytes;
          var dir = await getApplicationDocumentsDirectory();
          final name = p.join(dir.path, fileName + ".pdf");//From Alberto Miola's answer
          File file = File(name);
          print(dir.path);
          File urlFile = await file.writeAsBytes(bytes);
          return urlFile;
        } catch (e) {
          throw Exception("Error opening url file");