首页 > 解决方案 > 如何在 Flutter web 中使用锚元素?

问题描述

当前设置(使用launch

我想在我的 Flutter Web 应用程序中使用链接,目前这样做(使用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,
      ),
    ),
  ),
);

使用什么有效launch

这段代码片段做对了三件事:

什么不起作用_launch

<a>但是,与在常规 HTML中使用锚元素相比,我在网络上遇到了许多问题:

截屏

尤其是在 Safari 上不起作用的链接以及未显示的链接预览,我真的需要得到解决才能获得流畅的网络体验。我该如何做到这一点?

标签: htmlflutterdartflutter-web

解决方案


解决方案

这个url_launcher实际上有一个没有多少人知道的内置解决方案:链接库。这个库提供了一个Link小部件来修复所有提到的问题:

  • 在悬停时显示链接预览(通过在 Web 上插入<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),
          ),
        ),
      );
    },
  ),
);

如您所见,您只需指定uri应在点击时打开的内容以及target定义链接打开方式的内容。通读文档以了解更多信息

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

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


推荐阅读