在 Flutter 中实现 App Links(Android)和 Universal Links(iOS)可以让应用通过 HTTP/HTTPS 链接直接打开特定页面,提升用户体验。以下是实现步骤:
Android 配置(App Links)
-
修改 android/app/src/main/AndroidManifest.xml:
在 <activity> 标签内添加 Intent 过滤器:
<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" />
<data
android:scheme="https"
android:host="yourdomain.com"
android:pathPrefix="/path" />
</intent-filter>
-
创建 assetlinks.json 文件:
在域名根目录放置 /.well-known/assetlinks.json,内容如下:
[{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.example.yourapp",
"sha256_cert_fingerprints": ["YOUR_APP_SHA256_FINGERPRINT"]
}
}]
使用以下命令获取 SHA256 指纹:
keytool -list -v -keystore your-keystore.jks
iOS 配置(Universal Links)
-
修改 ios/Runner/Runner.entitlements:
添加以下内容:
<key>com.apple.developer.associated-domains</key>
<array>
<string>applinks:yourdomain.com</string>
</array>
-
创建 apple-app-site-association 文件:
在域名根目录放置 /.well-known/apple-app-site-association(无后缀),内容如下:
{
"applinks": {
"details": [
{
"appIDs": ["TEAMID.bundle.identifier"],
"components": [
{
"/": "/path/*",
"comment": "匹配特定路径"
}
]
}
]
}
}
Flutter 代码处理
使用 uni_links 包处理链接:
-
添加依赖:
dependencies:
uni_links: ^0.5.1
-
监听链接:
import 'package:uni_links/uni_links.dart';
void initUniLinks() {
getInitialUri().then((Uri? uri) {
// 处理冷启动链接
if (uri != null) handleDeepLink(uri);
});
uriLinkStream.listen((Uri? uri) {
// 处理应用运行中的链接
if (uri != null) handleDeepLink(uri);
});
}
void handleDeepLink(Uri uri) {
if (uri.path == '/path') {
Navigator.pushNamed(context, '/target-page');
}
}
注意事项
- 确保 HTTPS 和文件可访问(无重定向)。
- 测试链接:Android 使用
adb shell am start -a android.intent.action.VIEW -d "https://yourdomain.com/path"。
- iOS 需在真机测试,模拟器不支持 Universal Links。
完成以上步骤后,应用即可通过指定链接直接打开并跳转至对应页面。