Flutter InAppWebView点击地图链接无法唤起外部地图应用如何解决
问题原因
InAppWebView默认会拦截所有页面跳转请求,在组件内部直接加载目标链接,不会主动将特殊协议/第三方服务链接交给系统处理,因此谷歌地图链接会直接在WebView内打开,不会唤起外部地图应用。
解决步骤
- 第一步:添加
url_launcher依赖用于唤起系统级应用跳转,在pubspec.yaml中添加:
dependencies: url_launcher: ^6.2.0
- 第二步:完成平台侧配置
- 安卓端:在
android/app/src/main/AndroidManifest.xml的<manifest>标签下添加应用可见性规则:
<queries> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="https" /> </intent> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="geo" /> </intent> </queries>- iOS端:在
ios/Runner/Info.plist的<dict>标签下添加跳转白名单:
<key>LSApplicationQueriesSchemes</key> <array> <string>https</string> <string>maps</string> <string>geo</string> </array> - 安卓端:在
- 第三步:给
InAppWebView添加navigationDelegate回调,拦截谷歌地图相关链接,拦截后交给url_launcher处理,阻止WebView内部加载,修改后的完整代码如下:
child: InAppWebView( initialUrlRequest: URLRequest( url: Uri.parse("https://mywebsite.com"), ), // 新增导航拦截配置 navigationDelegate: (NavigationRequest request) async { // 匹配谷歌地图相关链接 if (request.url.host == 'www.google.com' && request.url.path.startsWith('/maps/')) { if (await canLaunchUrl(request.url)) { // 交给系统打开,会自动唤起已安装的地图应用 await launchUrl(request.url, mode: LaunchMode.externalApplication); } // 终止WebView内部加载该链接 return NavigationActionPolicy.CANCEL; } // 其他链接继续在WebView内部加载 return NavigationActionPolicy.ALLOW; }, androidOnGeolocationPermissionsShowPrompt: (InAppWebViewController controller, String origin) async { return GeolocationPermissionShowPromptResponse( origin: origin, allow: true, retain: true ); }, initialOptions: options, onWebViewCreated: (InAppWebViewController controller) { _webViewController = controller; }, androidOnPermissionRequest: (InAppWebViewController controller, String origin, List<String> resources) async { return PermissionRequestResponse(resources: resources, action: PermissionRequestResponseAction.GRANT); } ),
补充说明
如果需要支持其他第三方链接的外部唤起,比如电话、短信、邮件链接,只需要在navigationDelegate中新增对应的规则匹配即可,通用逻辑一致:匹配到目标链接后拦截,交由url_launcher打开,返回NavigationActionPolicy.CANCEL终止WebView内部加载。
内容的提问来源于stack exchange,提问作者Viral Panchal
相关产品推荐
相关产品推荐

