关于 flutter-setup-declarative-routing
为 Flutter 开发者提供基于 go_router 的路由与深度链接实施指南,涵盖路由配置、平台链接设置和嵌套导航。
主要功能
- 01配置 GoRouter 路由树
- 02设置 Web 路径 URL 策略
- 03配置 Android 与 iOS 深度链接
- 04使用 StatefulShellRoute 实现嵌套导航
- 05通过扩展方法执行程序化导航
适用场景
- 01为 Flutter 应用建立声明式路由
- 02让平台链接打开指定页面
- 03实现保留状态的底部导航分支
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ flutter/ agent-plugins --skill flutter-setup-declarative-routing安装后在 Claude Code 中输入/flutter-setup-declarative-routing确认已加载。
详细介绍
实现路由和深度链接
目录
核心概念
使用 go_router 软件包在 Flutter 中声明式地配置路由。它提供了强大的 API,可处理复杂的路由场景、深度链接和嵌套导航。
- GoRouter:定义应用路由树的核心配置对象。
- GoRoute:将 URL 路径映射到 Flutter 屏幕的标准路由。
- ShellRoute / StatefulShellRoute:将子路由封装在持久的 UI 外壳中(例如
BottomNavigationBar)。StatefulShellRoute会保留并行导航分支的状态。 - 路径 URL 策略:从 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 filter。
<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实现外壳组件。
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(),
),
],
),
],
),
],
);
示例
高保真外壳组件实现
实现 UI 外壳,使用 StatefulNavigationShell 处理分支切换。
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