如何在Flutter InAppWebView中为Fetch请求返回自定义响应?
拦截InAppWebView的Fetch请求并返回自定义响应
你混淆了shouldInterceptFetchRequest和shouldInterceptRequest的作用:前者仅用于修改Fetch请求的参数(比如URL、请求头),真正能拦截请求并返回自定义响应的是shouldInterceptRequest回调,它和原生Android的shouldInterceptRequest功能一致。
具体实现步骤:
- 在
InAppWebView的配置中启用必要的Web设置(比如JavaScript),并注册shouldInterceptRequest回调。 - 在回调中判断请求URL是否匹配目标精灵资源地址。
- 构造自定义的
WebResourceResponse,将你生成的JSON内容转为字节流返回。
示例代码:
InAppWebView( initialUrlRequest: URLRequest(url: Uri.parse("你的地图页面地址")), initialSettings: InAppWebViewSettings( javaScriptEnabled: true, allowFileAccess: true, // 根据需要添加其他设置 ), shouldInterceptRequest: (controller, request) async { final targetUrl = "https://content/sprite/sprite@2x.json"; if (request.url.toString() == targetUrl) { // 这里替换为你的自定义JSON内容 final customJson = ''' { "你的精灵资源JSON结构": "对应内容" } '''; // 构造响应返回 return WebResourceResponse( data: Uint8List.fromList(utf8.encode(customJson)), mimeType: "application/json", encoding: "utf-8", headers: {"Content-Type": "application/json; charset=utf-8"}, ); } // 非目标请求,返回null让WebView正常处理 return null; }, );
关键说明:
shouldInterceptRequest会拦截所有类型的请求(包括Fetch、XHR、普通资源加载),返回WebResourceResponse后,WebView会直接使用这个响应结果,不再发起原请求。- 务必设置正确的MIME类型(
application/json)和编码,确保mapbox-gl能正确解析你的自定义JSON。 - 如果JSON内容是动态生成或从本地读取的,只需将其转为
Uint8List传入data字段即可。
内容的提问来源于stack exchange,提问作者pmichel
相关产品推荐
相关产品推荐

