问题描述
Flutter升级之前还是好使的,升级后就打不开微信了。开始用了过期的API:await launch(request.url,);
以为是过期的API的问题呢,结果改了一通发现并不是,
代码修改
final url = Uri.parse(request.url);
// await launch(request.url,);
// await launchUrl(Uri.parse(request.url),
// mode: LaunchMode.platformDefault);
try {
// 检查是否支持该 Scheme
if (await canLaunchUrl(url)) {
// 强制在外部应用(微信)中打开
final bool nativeAppLaunchSucceeded =
await launchUrl(
url,
mode:
LaunchMode.externalApplication, // 关键参数!
);
if (!nativeAppLaunchSucceeded) {
await launchUrl(
url,
mode: LaunchMode
.externalNonBrowserApplication,
);
}
} else {
throw '未安装微信或无法跳转';
}
} catch (e) {
LogsUtil.e('跳转失败: $e');
// 提示用户手动操作(如复制链接)
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("跳转微信失败,请检查是否安装微信")),
);
}
iOS对于url_launcher插件,用户需要在Info.plist中添加LSApplicationQueriesSchemes键来声明要查询的URL方案。例如,要打开微信,需要添加:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>weixin</string>
<string>wechat</string>
</array>
这个之前已经加过了,
url_launcher 仍失效,无法调起APP
根本原因是:
在Xcode 16和iOS 18环境中,url_launcher可能存在兼容性问题。具体表现为"type 'UIApplication' does not conform to protocol 'Launcher'"错误,这是由于iOS SDK中open方法增加了@MainActor和@Sendable修饰导致签名不匹配。
解决方案:
升级url_launcher_ios到6.3.1版本,可以通过dependency_overrides强制指定版本:
dependency_overrides:
url_launcher: ^6.3.1
看了引用的版本:
启动URL的插件 https://github.com/flutter/plugins/tree/master/packages/url_launcher
url_launcher: ^6.2.4
目前最新的是6.3.2了:
https://pub.dev/packages/url_launcher/versions
意外的是这个又需要dartSDK 3.2以上,而现在引用的是3.1.2,升级又要改一通。
无奈采用第二种方案,替换url_launcher中的方法:
搜索protocol Launcher
替换为:
protocol Launcher {
/// Returns a Boolean value that indicates whether an app is available to handle a URL scheme.
func canOpenURL(_ url: URL) -> Bool
/// Attempts to asynchronously open the resource at the specified URL.
func open(
_ url: URL,
options: [UIApplication.OpenExternalURLOptionsKey: Any],
completionHandler completion: (@MainActor @Sendable(Bool) -> Void)?)
}
/// Launcher is intentionally a direct passthroguh to UIApplication.
@available(iOS 10.0, *)
extension UIApplication: Launcher {}
运行OK!