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

Flutter中使用url_launcher打开URL报错“Cant open URL”求助

解决url_launcher无法打开URL的问题

1. 检查依赖与平台配置

  • 确保pubspec.yaml中引入了最新版本的url_launcher:
    dependencies:
      url_launcher: ^6.2.5 # 替换为当前最新版本
    
  • Android平台:在android/app/src/main/AndroidManifest.xml中补充必要权限:
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Android 11及以上需添加查询权限 -->
    <queries>
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="https" />
        </intent>
    </queries>
    
  • iOS平台:在ios/Runner/Info.plist中添加URL白名单:
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>https</string>
    </array>
    

2. 修复代码中的问题

你的代码存在几处关键问题:canLaunch已过时、缺少错误排查逻辑、参数配置冲突。修改后的代码如下:

import 'package:url_launcher/url_launcher.dart';

Future<void> _openURL(String url) async {
  final Uri uri = Uri.parse(url);
  if (await canLaunchUrl(uri)) {
    await launchUrl(
      uri,
      mode: LaunchMode.inAppWebView, // 替代原forceWebView参数
      webViewConfiguration: const WebViewConfiguration(
        enableJavaScript: true, // 根据业务需求决定是否开启
      ),
    );
  } else {
    // 打印错误信息辅助排查
    print('无法打开URL: $url');
  }
}

// 使用示例
ListTile(
  title: const Text('Google'),
  onTap: () {
    _openURL('https://www.google.de/');
  },
);

3. 额外排查点

  • 确认测试设备/模拟器有正常网络连接
  • 检查URL格式是否完整(必须包含http://或https://前缀)
  • 若用模拟器测试出现问题,建议切换到真机验证,部分模拟器存在浏览器配置异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:59:50