如何在Flutter应用中使用url_launcher打开URL并解决无法打开报错
url_launcher 无法打开URL报错的解决方案
- 完成平台权限配置
该问题90%以上是因为缺少平台端的URL查询权限配置导致:- Android端:如果你的项目
targetSdkVersion >= 30(适配Android 11及以上版本),需要在android/app/src/main/AndroidManifest.xml的<manifest>根标签下添加如下查询配置:
<queries> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="https" /> </intent> <!-- 如果需要打开http、tel、sms等其他scheme的链接,也可以对应添加配置 --> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="http" /> </intent> </queries>- iOS端:需要在
ios/Runner/Info.plist的<dict>标签下添加如下查询白名单配置:
<key>LSApplicationQueriesSchemes</key> <array> <string>https</string> <string>http</string> <!-- 其他需要打开的scheme也可以添加到这里 --> </array> - Android端:如果你的项目
- 替换废弃API
你目前使用的canLaunch、launch方法以及forceSafariVC、forceWebView参数都是url_launcher 6.0.0之后的废弃API,新版SDK中这些API已经失效,需要替换为新的API写法:
import 'package:url_launcher/url_launcher.dart'; Future <void> _openURL(String url) async{ // 先把字符串转为Uri对象 final Uri targetUri = Uri.parse(url); if(await canLaunchUrl(targetUri)) { await launchUrl( targetUri, // 用LaunchMode枚举替代原来的force参数,inAppWebView对应之前的forceWebView: true mode: LaunchMode.inAppWebView, ); } else{ throw 'Cant open URL'; } } // 调用逻辑保持不变 ListTile( title: Text('Google'), onTap: () { _openURL('https://www.google.de/'); } ),
- 额外排查点
如果修改后还是报错,可以先检查传入的URL格式是否合法,有没有多余空格、拼写错误,也可以把canLaunchUrl的返回值打印出来辅助排查。
内容的提问来源于stack exchange,提问作者Dalon
相关产品推荐
相关产品推荐

