如何在Flutter应用程序中分享图片文件给其他应用程序

4
我有一个应用程序,它向用户展示一张图片。我将该图像以链接的形式保存在MySQL数据库中,并将图像保存在服务器上的文件夹中。现在我尝试让用户可以从我的应用程序分享该图像到其他应用程序(如WhatsApp或Facebook)。
我使用了share_plus 3.0.5包来实现这个功能: share_plus 3.0.5
  await Share.shareFiles([//////////////////here/////////////], text: 'Image Shared');

使用此代码获取图像:

  Future MakeShare() async {
var response = await http.get(
    Uri.parse("https://*********/ImageMakeShare.php?ID=" + widget.IDS.toString()),
    headers: {"Accept": "application/json"});

setState(() {

  var convertDataToJson = json.decode(response.body);
  dataImage = convertDataToJson['result'];
  if (dataImage != null) {

    imageMaine = dataImage[0]['image'];

}}); }

我试图使它变得像那样

  await Share.shareFiles([imageMaine ], text: 'Image Shared');

但我遇到了错误:

E/flutter (10763): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(https:/*******0ee2e.png (No such file or directory), null, null, null)

现在我需要知道如何使用户能够将该图像分享到其他应用程序中。
有人可以帮我吗?

很高兴能看到错误以帮助您解决问题。 - Gabriel Costache
@GabrielCostache 你好兄弟,问题已经更新。 - M Al
4个回答

8

文档中可以看出,shareFiles()函数期望接收一个字符串列表,指向设备上的本地路径。您正在传递一个URI(imageMaine),它不是本地路径,因此该插件会抛出异常。

如果您想要分享一个链接,则应使用share()函数。 如果您想要分享文件,则应首先获取您的文件,然后使用shareFiles函数发送它:

  final url = Uri.parse("myLink");
  final response = await http.get(url);
  await File('/yourPath/myItem.png').writeAsBytes(response.bodyBytes);

  await Share.shareFiles(['/yourPath/myItem.png'], text: 'Image Shared');

你好兄弟 / 首先谢谢你的回答 / 我应该写什么 ('/yourPath/myItem.png')?我从哪里获取路径? - M Al
你可以使用路径提供程序 https://pub.dev/packages/path_provider - Gabriel Costache
它有一些问题,我已经分享了一个新的答案,里面包含了完整的解决方案。 - undefined

1
  static Future<String> shareScreenShort(String title, {required GlobalKey previewContainer, int originalSize = 1600}) async {
    try {
      RenderRepaintBoundary boundary = previewContainer.currentContext!.findRenderObject() as RenderRepaintBoundary;
      double pixelRatio = originalSize / MediaQuery.of(previewContainer.currentContext!).size.width;
      ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();

      String filePathAndName = Service.documentDirectoryPath + '/images/$title.png';
      File imgFile = File(filePathAndName);
      await imgFile.writeAsBytes(pngBytes);
      await Share.shareXFiles(
        [XFile(imgFile.path)],
        sharePositionOrigin: boundary.localToGlobal(Offset.zero) & boundary.size,
        text: title,
      );

      return "success";
    } catch (ex) {
      return ex.toString();
    }
  }

你能分享一下进口商品吗? - undefined

1
您可以使用我的库app_utils,它允许您使用提供的参数启动Android和iOS。您可以将图像URI作为参数传递给其他应用程序。

例如:

await AppUtils.launchApp( androidPackage: "com.whatsapp", iosUrlScheme: "whatsapp://", params: {"imageUrl": "https://image.png"});


你好兄弟 / 非常感谢,但我不是从链接分享图片,我是从数据库中获取然后分享,它不是一个链接 / 同时,我不会指定用户将图像发送到哪个应用程序。 - M Al
首先,尝试将您的图像保存在文件目录中,然后使用文件路径进行共享。 - Vishesh Pandey
当您引用自己的内容时,请务必阅读Stack Overflow的自我推广政策 - Jeremy Caney

-1
将用户名和网络图片URL传递到此方法中,它将返回XFile。
fileFromImageUrl(String url, String userName) async {
        final response = await http.get(
          Uri.parse(url),
        );
    
        final documentDirectory = await getApplicationDocumentsDirectory();
    
        var randomNumber = Random();
    
        final file = File(
          join(
            documentDirectory.path,
            "${randomNumber.nextInt(100)}_$userName.png",
          ),
        );
    
        file.writeAsBytesSync(response.bodyBytes);
    
        return XFile(file.path);
      }

像这样调用这个方法:

XFile fileForShare = await fileFromImageUrl(
                      fileURL, empName);

Share.shareXFiles(
                    [fileForShare],
                    text: widget.postData.title.toString(),
                 );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接