如何修复‘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
相关产品推荐
相关产品推荐

