Flutter中使用GoRouter通过Deep Link获取Uri参数的方法
用GoRouter处理Deep Link查询参数的方案
你完全可以借助GoRouter自身的RouteState对象获取Deep Link中的查询参数,无需修改路由路径配置,也不用依赖第三方库。具体实现步骤如下:
1. 在Login页面的路由builder中获取参数
修改你的login路由的builder方法,从state.queryParams中提取p参数,然后传递给Login组件:
GoRoute( path: 'login', parentNavigatorKey: _rootNavigatorKey, builder: (context, state) { // 从Deep Link的查询参数中获取p的值 final pValue = state.queryParams['p']; // 将参数传递给Login组件 return Login(p: pValue); }, routes: loginRouter, ),
对应的Login组件需要接收参数:
class Login extends StatelessWidget { final String? p; const Login({super.key, this.p}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('登录')), body: Center( // 使用获取到的参数 child: Text('Deep Link传入的参数p: $p'), ), ); } }
2. 确保iOS端的URL Scheme配置正确
在iOS项目的Info.plist中添加对应的URL Scheme配置,确保系统能识别customScheme://开头的链接:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>customScheme</string> </array> <key>CFBundleURLName</key> <string>myHost.name.com</string> </dict> </array>
3. 测试验证
继续使用你原来的终端命令测试:
xcrun simctl openurl booted "customScheme://myHost.name.com/login?p=0"
此时模拟器会直接跳转到Login页面,并且能正确显示参数p=0。
这种方式完全基于GoRouter原生能力,不会像uni_links那样干扰Flutter的Deep Link导航逻辑,也不需要在路由路径中提前定义参数格式,正好满足你的需求。
内容的提问来源于stack exchange,提问作者김상현
相关产品推荐
相关产品推荐

