Flutter应用中指定Deep Link跳转浏览器而非应用的实现方法
解决Flutter Deep Link特定URL跳转浏览器的问题
当然可以实现,核心思路是在Deep Link触发时拦截URL,判断是否属于指定规则(比如/unsubscribe路径),若是则调用系统浏览器打开,否则正常走应用内逻辑。以下是具体实现方案:
一、Flutter跨平台拦截处理(推荐)
通过Flutter层统一处理URL判断,无需分别修改两端原生代码,逻辑更统一:
- 先确保安装了
url_launcher插件(用于打开系统浏览器),在pubspec.yaml添加依赖:
dependencies: url_launcher: ^6.2.5
- 根据你使用的路由框架,添加拦截逻辑:
示例1:使用GoRouter的场景
GoRouter( routes: [ // 你的应用内路由配置 ], redirect: (context, state) { final uri = state.uri; // 判断是否为退订类链接 if (uri.path.startsWith('/unsubscribe')) { // 调用系统浏览器打开该URL launchUrl(uri, mode: LaunchMode.externalApplication); // 返回null表示不触发应用内路由跳转 return null; } // 其他URL正常走应用内路由 return null; }, );
示例2:直接监听Deep Link的场景
import 'package:url_launcher/url_launcher.dart'; import 'package:uni_links/uni_links.dart'; Future<void> initDeepLinkListener() async { // 处理应用启动时的初始Deep Link final initialUri = await getInitialUri(); if (initialUri != null) _handleDeepLink(initialUri); // 监听应用运行中的Deep Link跳转 uriLinkStream.listen((Uri? uri) { if (uri != null) _handleDeepLink(uri); }); } void _handleDeepLink(Uri uri) { if (uri.path.startsWith('/unsubscribe')) { // 打开系统浏览器 launchUrl(uri, mode: LaunchMode.externalApplication); } else { // 正常处理应用内页面跳转 Navigator.pushNamed(context, uri.path); } }
二、原生端补充拦截(可选)
如果需要在原生层做额外拦截,可分别修改Android和iOS代码:
Android端(MainActivity.kt)
override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) val uri = intent?.data uri?.let { if (it.path?.startsWith("/unsubscribe") == true) { val browserIntent = Intent(Intent.ACTION_VIEW, it) browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(browserIntent) finish() return } // 其他URL交给Flutter处理 } }
iOS端(AppDelegate.swift)
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { if url.path.hasPrefix("/unsubscribe") { UIApplication.shared.open(url, options: [:], completionHandler: nil) return false // 返回false表示不交给Flutter处理 } // 其他URL交给Flutter处理 return GeneratedPluginRegistrant.register(with: self) }
内容的提问来源于stack exchange,提问作者Zeone line
相关产品推荐
相关产品推荐

