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

Flutter share_plus包Android端抛出IllegalArgumentException问题排查

Android端share_plus分享临时文件报错的解决方法

问题原因

Android上share_plus依赖FileProvider实现安全文件分享,你当前用getTemporaryDirectory()获取的是App内部私有临时目录(路径为/data/user/0/xxx/cache/),而share_plus在处理时会尝试将文件复制到外部缓存的share子目录,但你的App的FileProvider未配置对应目录的访问权限,导致抛出「找不到配置根目录」的异常。

解决方案

方案1:改用外部缓存目录保存文件(推荐)

外部缓存目录属于App的外部存储区域,默认被share_plus的FileProvider配置覆盖,无需额外修改Android项目配置:

修改代码中获取临时目录的逻辑:

var res = await http.post(
    Uri.parse(url),
    body: {"document_html": htmlString},
);

// 替换getTemporaryDirectory为外部缓存目录
var temp = await getExternalCacheDirectory();

File file = File("${temp!.path}/testfile.pdf");
file = await file.writeAsBytes(res.bodyBytes);

Share.shareFiles([file.absolute.path]).catchError((err) {
    print(err);
}); 

方案2:配置FileProvider包含内部临时目录

如果必须使用内部临时目录,需修改Android项目配置:

  1. 在android/app/src/main/res/xml目录下创建(或修改)file_paths.xml,添加内部缓存目录的配置:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 保留原有配置,新增内部缓存目录的访问权限 -->
    <cache-path name="internal_cache" path="."/>
</paths>
  1. 确保AndroidManifest.xml中的FileProvider引用了该配置:
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths"/>
</provider>

说明

方案1更简单直接,因为外部缓存目录本身就是为跨App共享文件设计的;而内部临时目录默认属于App私有,必须额外配置FileProvider才能被其他App访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:40:33