Flutter中InAppWebView如何引用应用文档目录文件?
解决InAppWebView读取应用文档目录文件时自动添加assets/的问题
核心问题是你没有正确配置WebViewAssetLoader的路径处理器,导致WebView默认只会解析assets目录的内容。以下是官方支持的正确配置方法:
步骤1:获取应用文档目录路径
先通过path_provider包获取应用的私有文档目录路径(需先在pubspec.yaml添加该依赖):
import 'package:path_provider/path_provider.dart'; // 在合适的异步代码块中获取路径 final docsDir = await getApplicationDocumentsDirectory(); final pathdir = docsDir.path;
步骤2:配置InternalStoragePathHandler
取消注释InternalStoragePathHandler,将指定的URL前缀映射到你的应用文档目录:
return InAppWebView( initialSettings: InAppWebViewSettings( webViewAssetLoader: WebViewAssetLoader(pathHandlers: [ // 把"/docs/"前缀映射到应用文档目录 InternalStoragePathHandler( path: "/docs/", directory: pathdir, ), // 保留AssetsPathHandler以继续访问assets资源(如果需要) AssetsPathHandler(path: "/assets/") ]), allowFileAccess: true, allowFileAccessFromFileURLs: true, // 可选,增强文件访问权限 allowUniversalAccessFromFileURLs: true, // 可选,根据需求开启 ), onConsoleMessage: (controller, consoleMessage) { print(consoleMessage.message); }, initialUrlRequest: URLRequest( url: WebUri.uri(Uri.parse("http://localhost:8080/assets/wwwroot/index.html")) ), onWebViewCreated: (controller) { // 现在可以通过/docs/前缀访问文档目录的文件 controller.loadUrl( urlRequest: URLRequest( url: WebUri.uri(Uri.parse("http://localhost:8080/docs/Floor Plan/Unit Floor Plan1.pdf")) ) ); }, );
关键说明
InternalStoragePathHandler是inappwebview官方提供的本地存储目录映射处理器,通过指定path(URL前缀)和directory(本地目录路径),就能让WebView通过该前缀访问对应本地目录的文件。- 保留
AssetsPathHandler可以继续正常访问assets目录下的资源,避免影响原有逻辑。
替代方案:直接使用file://协议
如果不需要通过HTTP服务器访问,也可以直接用file协议加载文档目录的文件,注意路径要正确编码:
final pdfPath = "${docsDir.path}/Floor Plan/Unit Floor Plan1.pdf"; final encodedPath = Uri.encodeFull(pdfPath); controller.loadUrl( urlRequest: URLRequest( url: WebUri.uri(Uri.parse("file://$encodedPath")) ) );
Android 10及以上版本如果遇到访问问题,可在AndroidManifest.xml中添加:
<application android:requestLegacyExternalStorage="true">
内容的提问来源于stack exchange,提问作者MiguelG
相关产品推荐
相关产品推荐

