Flutter 如何在资产文件夹上共享图像?

问题描述

使用此代码,我不断收到错误“ENOENT(没有这样的文件或目录),空,空,空)”。如何共享资产文件夹中的文件

Directory directory = await getApplicationDocumentsDirectory();
    Share.shareFiles(['${directory.path}/baws.png'],text: 'Great picture');

解决方法

您面临的问题来自方法 getApplicationDocumentsDirectory(); 它没有为您提供正确的路径。

它为您提供了应用商店数据所在隐藏目录的路径。

您可能希望使用以下内容更新您的代码:

// old code
Share.shareFiles(['${directory.path}/baws.png'],text: 'Great picture');


// new one
Share.shareFiles(['assets/images/baws.png'],text: 'Great picture');

不要忘记将您的 'baws.png' 放在名为 assets 的文件夹和名为 image 的子文件夹中以匹配示例,并在您的 pubspec.yaml

文件夹 assets 需要位于项目目录的根目录下。

您可以在 official documentation here.

上找到更多信息 ,

首先以字节为单位获取图像并复制到临时文件。

      final ByteData bytes = await rootBundle.load('assets/image.jpg');
      final Uint8List list = bytes.buffer.asUint8List();

      final tempDir = await getTemporaryDirectory();
      final file = await new File('${tempDir.path}/image.jpg').create();
      file.writeAsBytesSync(list);

然后用share包来共享,应该可以了;

Share.shareFiles(['${file.path}'],text: 'Great picture');