使用share_plus包的shareXFiles方法出现分享回调错误求助
错误信息
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
相关产品推荐
相关产品推荐

