Files
tuiche/lib/pages/mh_page/component/jd.dart

53 lines
1.8 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:convert';
import 'package:url_launcher/url_launcher.dart';
class JDLauncher {
/// 跳转京东店铺App 优先)
static Future<void> openShop(String shopUrlOrShortLink) async {
final isShortLink = shopUrlOrShortLink.contains("3.cn");
if (isShortLink) {
// 如果是短链接,比如 https://3.cn/xxxxx直接尝试打开即可
await _launchJD(shopUrlOrShortLink);
} else {
// 如果是普通店铺链接,比如 https://mall.jd.com/index-xxxxxxx.html
final jdAppUrl = _buildJDAppUrl("m", {"url": shopUrlOrShortLink});
await _launchJD(jdAppUrl, fallbackUrl: shopUrlOrShortLink);
}
}
/// 跳转京东商品详情页(传入 SKU
static Future<void> openProduct(String skuId) async {
final webUrl = "https://item.jd.com/$skuId.html";
final jdAppUrl = _buildJDAppUrl("productDetail", {"skuId": skuId});
await _launchJD(jdAppUrl, fallbackUrl: webUrl);
}
/// 构建京东 App 的 scheme 跳转 URL
static String _buildJDAppUrl(String des, Map<String, dynamic> extraParams) {
final params = {
"category": "jump",
"des": des,
...extraParams,
};
final encoded = Uri.encodeComponent(jsonEncode(params));
return "openapp.jdmobile://virtual?params=$encoded";
}
/// 通用跳转逻辑(优先跳 App失败跳网页
static Future<void> _launchJD(String url, {String? fallbackUrl}) async {
try {
final uri = Uri.parse(url);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else if (fallbackUrl != null) {
await launchUrl(Uri.parse(fallbackUrl), mode: LaunchMode.externalApplication);
}
} catch (_) {
if (fallbackUrl != null) {
await launchUrl(Uri.parse(fallbackUrl), mode: LaunchMode.externalApplication);
}
}
}
}