Flutter中如何获取唤起App的Deep Linking链接以提取用户UID
解决Flutter深度链接无法获取链接的问题
1. 修正初始化时机
你当前在StatelessWidget的build方法中调用初始化逻辑,但build会随Widget重建多次执行,且异步操作的时序可能和MaterialApp启动冲突。建议改用StatefulWidget,在initState中完成初始化:
class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override void initState() { super.initState(); _initDeepLinks(); } Future<void> _initDeepLinks() async { try { // 获取首次唤起App的链接 final initialLink = await getInitialLink(); if (initialLink != null) { _processLink(initialLink); } // 监听App在后台时被链接唤起的情况 linkStream.listen((String? link) { if (link != null) { _processLink(link); } }, onError: (err) { print('链接监听异常: $err'); }); } on PlatformException catch (e) { print('平台异常: $e'); } } void _processLink(String link) { // 解析链接中的UID,示例链接格式:yourapp://profile/123456 final uri = Uri.parse(link); final uid = uri.pathSegments.first; // 提取出123456 print('获取到用户UID: $uid'); // 此处可跳转至用户个人主页,示例: // Navigator.push(context, MaterialPageRoute(builder: (_) => ProfilePage(uid: uid))); } @override Widget build(BuildContext context) { return const MaterialApp( home: SplashScreen(), ); } }
2. 检查AndroidManifest配置完整性
确保Intent Filter包含必要的分类,且data规则匹配你的链接格式:
<activity android:name=".MainActivity" android:exported="true"> <!-- 启动页Intent Filter --> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <!-- 深度链接Intent Filter --> <intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- 替换为你的scheme和host,pathPattern匹配任意路径以获取UID --> <data android:scheme="yourapp" android:host="profile" android:pathPattern=".*" /> </intent-filter> </activity>
注意:Android 12+必须添加android:exported="true",否则无法唤起App;android:autoVerify="true"用于支持HTTPS协议的App Links(可选)。
3. 正确测试深度链接
避免直接在模拟器中点击文本链接,建议用ADB命令测试(替换为你的包名和链接):
adb shell am start -W -a android.intent.action.VIEW -d "yourapp://profile/123456" com.your.app.package
4. 其他排查点
- 确认
uni_links依赖已添加到pubspec.yaml,并执行过flutter pub get - App从后台唤起时,
getInitialLink不会返回新链接,必须通过linkStream监听 - 检查链接的scheme、host是否和
data配置完全匹配
内容的提问来源于stack exchange,提问作者Abdul Haadi
相关产品推荐
相关产品推荐

