You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复‘canLaunch已废弃,应使用canLaunchUrl替代’的问题?

修复canLaunch废弃问题的方案

canLaunch和launch方法已被Flutter官方废弃,需替换为canLaunchUrl和launchUrl,同时要调整参数格式并修正原代码的逻辑错误,具体修改如下:

  • 替换废弃方法:把canLaunch改为canLaunchUrl,launch改为launchUrl
  • 转换URL格式:原字符串URL需转为Uri对象,用Uri.parse()处理
  • 修正判断逻辑:原代码的if判断逻辑写反了,应改为能打开URL时执行跳转,否则抛出异常

修改后的完整代码:

Container(
  child: Row(
    children: [
      Icon(
        Icons.facebook,
        color: Colors.blue,
      ),
      RichText(
        text: TextSpan(
          children: [
            TextSpan(
              style: defaultText,
              text: " Visit Facebook Page",
              recognizer: TapGestureRecognizer()..onTap = () async {
                final url = Uri.parse("https://www.facebook.com/minorijapaneserestaurant");
                if (await canLaunchUrl(url)) {
                  await launchUrl(url);
                } else {
                  throw "无法加载链接 $url";
                }
              }
            )
          ]
        ),
      )
    ],
  ),
)

注:若在Web平台使用,需在web/index.html中添加对应权限配置,移动端一般无需额外操作。

内容的提问来源于stack exchange,提问作者user20306517

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:10:32