如何在Flutter WebView中打开应用程序链接?

19
在Flutter中,我使用flutter webview插件来启动一个类似于以下的url:
flutterWebviewPlugin.launch(url)

或者

WebviewScaffold(
  url: url,
  appBar: new AppBar(title: Text(title), actions: [
    new IconButton(
      icon: const Icon(Icons.share),
      onPressed: () => Share.share(url),
    )
  ]),
  withZoom: true,
  withLocalStorage: true,
  withJavascript: true,
);

然而,如果打开的网页中有任何应用程序链接,比如:fb://profile,我会收到net::ERR_UNKNOWN_URL_SCHEME错误。

在安卓中,我发现解决方法是重写shouldOverrideUrlLoading,就像这里提到的那样,但是在flutter中该怎么办呢?


1
你能否把你的代码放上来? - diegoveloper
4个回答

19

您可以在pub.dev软件包中使用webview_flutter

WebView(
        initialUrl: 'https://my.url.com',
        javascriptMode: JavascriptMode.unrestricted,
        navigationDelegate: (NavigationRequest request)
        {
          if (request.url.startsWith('https://my.redirect.url.com'))
          {
            print('blocking navigation to $request}');
            _launchURL('https://my.redirect.url.com');
            return NavigationDecision.prevent;
          }

          print('allowing navigation to $request');
          return NavigationDecision.navigate;
        },
      )

你可以在pub.dev Packages中使用url_launcher来启动URL。

_launchURL(String url) async {
if (await canLaunch(url)) {
  await launch(url);
} else {
  throw 'Could not launch $url';
}}

我正在使用相同的代码来允许Flutter WebView(https://pub.dev/packages/webview_flutter)中的mailto方案。但是它会抛出错误,我无法构建APK文件。 - PARAS GUPTA
错误:不是常量表达式。 if (request.url.contains("mailto:")) { ^^^^^^^ 错误:方法调用不是常量表达式。 if (request.url.contains("mailto:")) { ^^^^^^^^ 错误:方法调用不是常量表达式。 launch(request.url); ^^^^^^ 错误:不是常量表达式。 navigationDelegate: (NavigationRequest request) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - PARAS GUPTA
我也在 Stack 上发布了这个问题,请查看 - https://stackoverflow.com/questions/65880593/how-to-allow-mailto-schemes-in-webview-flutter - PARAS GUPTA
这个答案现在已经过时了,并且也从包裹中移除了。 - Devendra Singh

3

那个插件有很多问题,例如gradle文件缺少对kotlin的依赖,AndroidManifest文件缺少活动声明等。我已经给开发者发了电子邮件,看看他是否仍在维护它。 - Herman

2

以下是解决 net::ERR_UNKNOWN_URL_SCHEME 错误的方法在这里

在你的 application 标签中添加以下行:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

如果您有网络安全配置,例如:android:networkSecurityConfig="@xml/network_security_config" 不需要像上面所示那样将明文流量设置为true,而是使用以下代码:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

cleartextTrafficPermitted 设置为 true

-2

您可以使用Web插件,例如

 @override
 Widget build(BuildContext context) {
   String url = widget.url;
   return Scaffold(
    body: Center(
    child : WebviewScaffold(
      url: "https://google.com",
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      withZoom: true,
      withLocalStorage: true,
     )
   ),
 );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接