You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用share_plus包的shareXFiles方法出现分享回调错误求助

问题解决:shareXFiles替换shareFiles后出现回调错误

错误信息

Share callback error, prior share-sheet did not call back, did you await it?

核心解决方法

1. 统一使用async/await替代then链式调用

代码中混合then和内部async函数可能导致异步流程混乱,无法正确等待分享操作完成,建议重构为全async/await写法:

void shareInvoice(String url, String uiid) async {
  try {
    final file = await _invoiceService.extractPDFromURL(url, uiid);
    final xfile = XFile(file.path);
    await Share.shareXFiles([xfile], text: 'PDF Document');
  } catch (e) {
    ToastService.error(e.toString());
  } finally {
    LoadingService.hide();
  }
}

2. 防止重复触发分享操作

错误的常见诱因是分享面板未关闭时再次调用shareXFiles,添加状态变量控制分享状态:

bool _isSharing = false;

void shareInvoice(String url, String uiid) async {
  if (_isSharing) return;
  _isSharing = true;
  
  try {
    final file = await _invoiceService.extractPDFromURL(url, uiid);
    final xfile = XFile(file.path);
    await Share.shareXFiles([xfile], text: 'PDF Document');
  } catch (e) {
    ToastService.error(e.toString());
  } finally {
    LoadingService.hide();
    _isSharing = false;
  }
}

3. 直接通过字节流创建XFile

绕过临时文件写入步骤,用下载的字节流直接生成XFile,避免路径或权限问题:

void shareInvoice(String url, String uiid) async {
  try {
    final bytes = await _invoiceRepository.downloadPdfFileFromURL(url);
    final xfile = XFile.fromData(
      bytes,
      name: 'invoice_$uiid.pdf',
      mimeType: 'application/pdf',
    );
    await Share.shareXFiles([xfile], text: 'PDF Document');
  } catch (e) {
    ToastService.error(e.toString());
  } finally {
    LoadingService.hide();
  }
}

4. 更新share_plus插件版本

旧版本share_plus可能存在shareXFiles的回调bug,执行命令更新至最新稳定版:

flutter pub upgrade share_plus

内容的提问来源于stack exchange,提问作者rafaelpadu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:23:16