flutter如何实现深度链接
在Flutter中如何实现深度链接功能?我想让用户通过点击外部链接直接跳转到App内的特定页面,比如商品详情或活动页。目前已经配置了Android的Intent Filter和iOS的URL Scheme,但在Flutter层不知道该如何处理路由解析。请问具体需要用到哪个插件?uni_links还是flutter_deeplink?如何区分冷启动和热启动的不同处理逻辑?另外,在Web端和桌面端是否也需要特殊适配?希望有完整实现方案和代码示例。
2 回复
Flutter可通过uni_links包实现深度链接。在pubspec.yaml中添加依赖,配置Android的intent-filter和iOS的URL types,然后在代码中监听链接事件即可处理传入的深度链接。
更多关于flutter如何实现深度链接的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中实现深度链接(Deep Linking)主要通过以下步骤完成,支持应用内页面跳转和从外部链接直接打开特定内容:
1. 添加依赖
在 pubspec.yaml 中添加:
dependencies:
uni_links: ^0.5.1 # 支持iOS/Android链接处理
go_router: ^5.0.0 # 推荐使用(或flutter_web_plugins)
2. 平台配置
Android(AndroidManifest.xml):
<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="yourapp" android:host="example.com"/>
</intent-filter>
iOS(Info.plist):
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.example.yourapp</string>
<key>CFBundleURLSchemes</key>
<array>
<string>yourapp</string>
</array>
</dict>
</array>
3. 代码实现
使用 go_router 处理路由:
final GoRouter router = GoRouter(
routes: [
GoRoute(
path: '/product/:id',
builder: (context, state) => ProductPage(id: state.params['id']!),
),
],
);
// 在MaterialApp中配置
MaterialApp.router(
routerConfig: router,
);
4. 链接监听
import 'package:uni_links/uni_links.dart';
String? _initialLink;
StreamSubscription? _sub;
Future<void> initUniLinks() async {
// 获取初始链接
_initialLink = await getInitialLink();
_handleLink(_initialLink);
// 监听链接变化
_sub = linkStream.listen(_handleLink);
}
void _handleLink(String? link) {
if (link != null) {
final uri = Uri.parse(link);
if (uri.pathSegments.contains('product')) {
router.push('/product/${uri.queryParameters['id']}');
}
}
}
@override
void dispose() {
_sub?.cancel();
super.dispose();
}
5. 测试链接
- App Links:
https://example.com/product?id=123 - Custom Scheme:
yourapp://example.com/product?id=123

