如何在 Flutter web 中使用 <a> 锚元素?

cre*_*not 4 html dart flutter flutter-web

当前设置(使用launch

我想在我的 Flutter Web 应用程序中使用链接,目前这样做(使用 package url_launcher

return MouseRegion(
  cursor: SystemMouseCursors.click,
  child: GestureDetector(
    onTap: () {
      launch('https://creativemaybeno.dev');
    },
    child: const Text(
      'my amazing link',
      style: TextStyle(
        decoration: TextDecoration.underline,
      ),
    ),
  ),
);
Run Code Online (Sandbox Code Playgroud)

使用什么有效launch

此代码片段正确执行了三件事:

  • 完全适用于移动设备
  • 在网页上悬停时显示单击光标
  • 在大多数情况下打开网络上的链接

使用什么不起作用launch

<a>然而,与在常规 HTML 中使用锚元素相比,我在网络上使用此方法存在许多问题:

  • 浏览器左下角不显示链接预览。这就是它在常规 HTML页面
    上的样子:

截屏

  • 链接打开速度似乎比常规网络应用程序中的链接

  • Safari 完全阻止我的链接(“阻止弹出窗口”)

特别是链接在 Safari 上不起作用以及链接预览未显示,我真的需要解决这个问题才能获得流畅的网络体验。我该如何实现这一目标?

cre*_*not 6

解决方案

url_launcher软件包实际上有一个内置的解决方案,但很多人都不知道:链接库。该库提供了一个Link小部件,可以解决所有提到的问题:

  • 在悬停时显示链接预览(通过<a>在网络上插入元素)。
  • 适用于所有浏览器(不会作为弹出窗口被阻止,永远不会)。
  • 打开速度与普通 HTML 页面一样快。
  • 默认情况下也适用于移动设备。

用法

Link小部件可以像这样使用:

return MouseRegion(
  cursor: SystemMouseCursors.click,
  child: Link(
    uri: Uri.parse('https://creativemaybeno.dev'),
    target: LinkTarget.blank,
    builder: (context, followLink) {
      return GestureDetector(
        onTap: followLink,
        child: const Text(
          'my amazing link',
          style: TextStyle(
            decoration: TextDecoration.underline,
            // The default link color according to the HTML living standard.
            // See https://html.spec.whatwg.org/multipage/rendering.html#phrasing-content-3,
            // which defines :link { color: #0000EE; }.
            color: Color(0xff0000ee),
          ),
        ),
      );
    },
  ),
);
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,您只需指定uri应该点击打开的 以及target定义如何打开链接的 。通读文档以了解更多信息

现在,该Link小部件为您提供了一个builder传递followLink回调的函数。您只需根据您想要的点击操作调用它(GestureDetector例如将其传递给 a)。
您不必Text像孩子一样使用小部件 - 您实际上可以使用任何东西,例如按钮。

请注意,锚点预览将在悬停在子窗口小部件占据的整个区域<a>上时显示。所以尽量不要让按钮/子项变得很大:)