How do I open a file from disk, in a Flutter app?

2019-05-23 07:28发布

问题:

In a Flutter app I have a dart file located at FlutterTest\sandbox\lib\my_widget\my_widget.dart.

And I have an image located at FlutterTest\sandbox\lib\my_widget\imgs\myImage.png.

From my_widget.dart how can I point a file to this image, something along the lines of new File("???\my_widget\myImage.png")?

Just to clarify, in Java I could do something like MyClass.class.getResource("myImage.png").toString().

By the way if I print(Directory.current.path) it gives me simply /. And if I try to list the contents of this directory it tells me: "Directory listing failed, path = '/' (OS Error: Permission denied, errno = 13)". So I don't actually know where the current directory is.

回答1:

You can directly access the file system but due to differences in android and iOS you'll probably end up using the path provider plugin. Also, see this flutter cookbook as they call it.

But if all you're trying to do is access a file from your build, you'll want to define it as an asset in your pubspec, and then access it using Flutter's AssetBundle (or Image.asset) rather than directly using File or Image.file. See the flutter documentation on assets.



标签: dart flutter