chatapp3-flutter/lib/shared/tools/sc_deep_link_handler.dart
2026-04-09 21:32:23 +08:00

61 lines
1.7 KiB
Dart
Raw Permalink 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:async';
import 'package:app_links/app_links.dart'; // 1. 替换导入
class SCDeepLinkHandler {
// 2. 创建 AppLinks 实例(通常作为单例,但也可以每次创建)
final AppLinks _ap = AppLinks();
StreamSubscription<Uri>? _lss; // 注意流类型变为 Uri
final _lnc = StreamController<String?>.broadcast();
Stream<String?> get linkNotifierStream => _lnc.stream;
Function(Uri)? _olrc;
Future<void> initDeepLinks({Function(Uri)? onLinkReceived}) async {
_olrc = onLinkReceived;
await _iln();
_sl();
}
Future<void> _iln() async {
try {
// 3. 使用实例方法获取初始链接,返回 Uri? 而不是 String?
Uri? initialLink = await _ap.getInitialLink();
if (initialLink != null) {
_ph(initialLink);
}
} catch (err) {
print('获取初始链接失败: $err');
}
}
void _sl() {
// 4. 使用 uriLinkStream 监听链接(流类型为 Uri
_lss = _ap.uriLinkStream.listen(
(Uri? link) {
// 注意uriLinkStream 可能直接发出 Uri而不是 String?
// 根据实际版本,可能是 Uri 或 String?,以下处理两者兼容
if (link != null) {
_ph(link);
}
},
onError: (err) {
print('监听链接流出错: $err');
},
);
}
// 5. 接收 Uri 类型参数(原来接收 String
void _ph(Uri uri) {
print('SCDeepLinkHandler 处理链接: $uri');
// 如果需要存储为字符串,可以使用 uri.toString()
_lnc.add(uri.toString());
_olrc?.call(uri);
}
void dispose() {
_lss?.cancel();
_lnc.close();
}
}