如何通过URL实现Flutter应用内指定页面的跳转?
Flutter实现分享URL跳转指定页面方案
一、配置深度链接(Deep Link)
首先需要为应用配置深度链接,让系统能识别专属URL协议并唤起你的应用。
Android 端配置
在android/app/src/main/AndroidManifest.xml的<activity>标签内添加intent-filter:
<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- 自定义URL协议,比如myapp:// --> <data android:scheme="myapp" /> </intent-filter>
iOS 端配置
在ios/Runner/Info.plist中添加URL Scheme配置:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>myapp</string> <!-- 和Android端一致的协议名 --> </array> </dict> </array>
如果需要用HTTPS链接(Universal Links),需额外配置苹果开发者后台和apple-app-site-association文件,这里先介绍基础自定义协议方案。
二、处理应用内跳转逻辑
配置好链接后,需在Flutter代码中解析传入的URL,跳转到对应页面。
基础路由(MaterialApp)实现
在MaterialApp中通过onGenerateRoute处理路由:
MaterialApp( onGenerateRoute: (settings) { // 解析传入的Uri final Uri? uri = settings.name != null ? Uri.parse(settings.name!) : null; if (uri != null && uri.scheme == 'myapp') { // 根据path和参数跳转对应页面 if (uri.path == '/product') { final String? productId = uri.queryParameters['id']; if (productId != null) { return MaterialPageRoute( builder: (context) => ProductDetailsPage(productId: productId), ); } } } // 默认跳转首页 return MaterialPageRoute(builder: (context) => HomePage()); }, );
使用GoRouter(推荐)
如果用go_router包管理路由,可直接在路由配置中匹配深度链接:
final GoRouter _router = GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return const HomePage(); }, ), GoRoute( path: '/product/:id', builder: (BuildContext context, GoRouterState state) { final String productId = state.params['id']!; return ProductDetailsPage(productId: productId); }, // 匹配深度链接 redirect: (context, state) { final Uri? uri = state.uri; if (uri.scheme == 'myapp' && uri.path == '/product') { final String? id = uri.queryParameters['id']; if (id != null) { return '/product/$id'; } } return null; }, ), ], );
三、实现分享功能
用share_plus包构造带参数的深度链接并分享:
- 先在
pubspec.yaml添加依赖:
dependencies: share_plus: ^7.2.1
- 分享按钮的点击逻辑:
ElevatedButton( onPressed: () async { // 构造带参数的深度链接,比如分享商品ID为123的页面 final String shareUrl = 'myapp://product?id=123'; await Share.share('查看这款商品:$shareUrl'); }, child: const Text('分享商品'), );
用户点击分享的链接后,系统会唤起你的应用,然后根据链接中的参数跳转到对应的页面。
内容的提问来源于stack exchange,提问作者Farid Ahmadov
相关产品推荐
相关产品推荐

