html - 如何在 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
这段代码片段做对了三件事:
- 完全适用于手机
- 在 web 上悬停时显示单击光标
- 在大多数情况下打开网页上的链接
什么不起作用_launch
<a>
但是,与在常规 HTML中使用锚元素相比,我在网络上遇到了许多问题:
- 浏览器左下角不显示链接预览。这是它在常规 HTML页面
上的样子:
链接的打开速度似乎比常规网络应用程序中的慢
Safari 完全阻止了我的链接(“阻止了弹出窗口”)
尤其是在 Safari 上不起作用的链接以及未显示的链接预览,我真的需要得到解决才能获得流畅的网络体验。我该如何做到这一点?
解决方案
解决方案
这个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>
锚点预览将在子窗口小部件占据的整个区域悬停时显示。所以尽量不要让按钮/孩子很大:)
推荐阅读
- java - Java Spring-boot:查找资源的问题
- php - 如果另一个多维数组中存在数组值,如何检查和替换数组
- button - 在 v-on:click 或 @click (Vue.js) 中的函数上传递变量
- java - 迭代时如何修改列表中的对象?
- python - 我们如何在 pytest 中接受一个命令行选项的多个值
- javascript - 有没有办法使用在位于子文件夹中的后台运行的 php 脚本的输出来更改 div 背景颜色?
- arrays - 如何删除搜索结果链接中第二个单词前面的空格?
- android - Android Studio 上的 Unity 初始化错误(找不到或无法加载 mscorlib.dll)
- jenkins - 如何使用 Jenkins 警告-ng-plugin - SonarQube 分析?
- android - 如何从具有多个孩子的 Firebase 中提取数据?