关于 flutter-setup-declarative-routing
用于在 Flutter 中通过 go_router 实现声明式路由和深层链接的开发技能,介绍路由配置、平台 URL 处理及保留导航状态的嵌套导航。
主要功能
- 01配置 GoRouter 和 GoRoute
- 02设置平台深层链接
- 03创建嵌套导航外壳
- 04保留导航分支状态
- 05验证 Android 和 iOS 链接
适用场景
- 01为 Flutter 应用初始化路由
- 02通过平台 URL 打开应用页面
- 03构建持久化底部导航栏
- 04测试 Android 和 iOS 深层链接
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ dhruvanbhalara/ skills --skill flutter-setup-declarative-routing安装后在 Claude Code 中输入/flutter-setup-declarative-routing确认已加载。
详细介绍
实现路由和深度链接
目录
核心概念
在 Flutter 中使用 go_router 包进行声明式路由。它为复杂路由场景、深度链接和嵌套导航提供了可靠的 API。
- GoRouter:定义应用路由树的核心配置对象。
- GoRoute:将 URL 路径映射到 Flutter 屏幕的标准路由。
- ShellRoute / StatefulShellRoute:将子路由包装在持久化 UI 外壳中(例如
BottomNavigationBar)。StatefulShellRoute会保留并行导航分支的状态。 - Path URL Strategy:从 Web URL 中移除默认的
#片段,这对于跨平台实现简洁的深度链接至关重要。
工作流:初始化应用和路由器
按照此工作流,使用 go_router 搭建新的 Flutter 应用,并配置根路由机制。
任务进度
- 创建 Flutter 应用。
- 添加
go_router依赖项。 - 为 Web/深度链接配置 URL 策略。
- 实现
GoRouter配置。 - 将路由器绑定到
MaterialApp.router。
1. 搭建应用
运行以下命令创建应用并添加所需的路由包:
flutter create <app-name>
cd <app-name>
flutter pub add go_router
2. 配置路由器
定义一个顶层 GoRouter 实例。使用 redirect 参数处理身份验证或基于状态的路由。
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
void main() {
// Use path URL strategy to remove the '#' from web URLs
usePathUrlStrategy();
runApp(const MyApp());
}
final GoRouter _router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'details/:id',
builder: (context, state) => DetailsScreen(id: state.pathParameters['id']!),
),
],
),
],
errorBuilder: (context, state) => ErrorScreen(error: state.error),
);
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _router,
title: 'Routing App',
);
}
}
工作流:配置平台深度链接
配置原生平台,以拦截特定 URL 并将其路由到 Flutter 应用。
任务进度
- 确定目标平台(iOS、Android 或两者)。
- 应用 Android 专属配置(Manifest + Asset Links)。
- 应用 iOS 专属配置(Plist + Entitlements + AASA)。
- 运行验证器 -> 检查错误 -> 修复。
如果配置 Android:
- 修改
AndroidManifest.xml:在.MainActivity的<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="http" android:host="yourdomain.com" />
<data android:scheme="https" />
</intent-filter>
- 托管
assetlinks.json:在https://yourdomain.com/.well-known/assetlinks.json提供以下 JSON。
[{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.yourcompany.yourapp",
"sha256_cert_fingerprints": ["YOUR_SHA256_FINGERPRINT"]
}
}]
如果配置 iOS:
- 修改
Info.plist:启用 Flutter 默认的深度链接处理器。 注意:如果使用第三方深度链接插件(例如app_links),请将其设为NO,以避免冲突。
<key>FlutterDeepLinkingEnabled</key>
<true/>
- 修改
Runner.entitlements:添加关联域名。
<key>com.apple.developer.associated-domains</key>
<array>
<string>applinks:yourdomain.com</string>
</array>
- 托管
apple-app-site-association:在https://yourdomain.com/.well-known/apple-app-site-association提供以下 JSON(不带.json扩展名)。
{
"applinks": {
"apps": [],
"details": [{
"appIDs": ["TEAM_ID.com.yourcompany.yourapp"],
"paths": ["*"],
"components": [{"/": "/*"}]
}]
}
}
验证循环
运行验证器 -> 检查错误 -> 修复。
- Android:使用 ADB 测试。
adb shell 'am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://yourdomain.com/details/123"' com.yourcompany.yourapp - iOS:在已启动的模拟器上使用
xcrun测试。xcrun simctl openurl booted https://yourdomain.com/details/123
工作流:实现嵌套导航
使用 StatefulShellRoute 实现持久化 UI 外壳(例如底部导航栏),以保留其子路由的状态。
任务进度
- 在
GoRouter配置中定义StatefulShellRoute.indexedStack。 - 为每个导航标签页创建
StatefulShellBranch实例。 - 使用
StatefulNavigationShell实现外壳 Widget。
final GoRouter _router = GoRouter(
initialLocation: '/home',
routes: [
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) {
return ScaffoldWithNavBar(navigationShell: navigationShell);
},
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsScreen(),
),
],
),
],
),
],
);
示例
高保真外壳 Widget 实现
实现使用 StatefulNavigationShell 处理分支切换的 UI 外壳。
class ScaffoldWithNavBar extends StatelessWidget {
const ScaffoldWithNavBar({
required this.navigationShell,
super.key,
});
final StatefulNavigationShell navigationShell;
void _goBranch(int index) {
navigationShell.goBranch(
index,
// Support navigating to the initial location when tapping the active tab.
initialLocation: index == navigationShell.currentIndex,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: navigationShell,
bottomNavigationBar: NavigationBar(
selectedIndex: navigationShell.currentIndex,
onDestinationSelected: _goBranch,
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
),
);
}
}
以编程方式导航
使用 go_router 提供的 context.go() 和 context.push() 扩展方法。
// Replaces the current route stack with the target route (Declarative)
context.go('/details/123');
// Pushes the target route onto the existing stack (Imperative)
context.push('/details/123');
// Navigates using a named route and path parameters
context.goNamed('details', pathParameters: {'id': '123'});
// Pops the current route
context.pop();
评论
支持 Markdown