Flutter 使用 url_launcher 从默认浏览器运行 url

gen*_*ser 3 flutter url-launcher

我正在使用url_launcher (6.1.5),我想在默认浏览器而不是应用程序内的 webView 中打开网址。

最新版本似乎不支持它,因为launch函数已被弃用,并且launchUrl不支持该forceWebView=false标志。

如何使用默认浏览器运行我的网址url_launcher

gen*_*ser 28

长话短说

您可以使用该LaunchMode.externalApplication参数。

await launchUrl(_url, mode: LaunchMode.externalApplication);
Run Code Online (Sandbox Code Playgroud)

更多信息

默认情况下,该mode值设置为LaunchMode.platformDefault,在大多数情况下为inAppWebView

更改mode解决了这个问题:

Future<void> openUrl(String url) async {
  final _url = Uri.parse(url);
  if (!await launchUrl(_url, mode: LaunchMode.externalApplication)) { // <--
    throw Exception('Could not launch $_url');
  }
}
Run Code Online (Sandbox Code Playgroud)

LaunchMode支持几个论点:

enum LaunchMode {
  /// Leaves the decision of how to launch the URL to the platform
  /// implementation.
  platformDefault,

  /// Loads the URL in an in-app web view (e.g., Safari View Controller).
  inAppWebView,

  /// Passes the URL to the OS to be handled by another application.
  externalApplication,

  /// Passes the URL to the OS to be handled by another non-browser application.
  externalNonBrowserApplication,
}
Run Code Online (Sandbox Code Playgroud)