flutter-setup-declarative-routing

flutter-setup-declarative-routing

热门

使用 `go_router` 等路由包配置 `MaterialApp.router`,实现高级基于 URL 的导航。适用于开发需要特定 Deep Linking(深度链接)支持及浏览器历史记录管理的 Web 应用或移动端 App。

2783Star
163Fork
更新于 2026/8/5
SKILL.md
只读
名称
flutter-setup-declarative-routing
描述

使用 `go_router` 等路由包配置 `MaterialApp.router`,实现高级基于 URL 的导航。适用于开发需要特定 Deep Linking(深度链接)支持及浏览器历史记录管理的 Web 应用或移动端 App。

实现路由与 Deep Linking

目录

核心概念

在 Flutter 中推荐使用 go_router 软件包实现声明式路由。它针对复杂的路由场景、Deep Linking(深度链接)和嵌套导航提供了强健且易用的 API。

  • GoRouter:核心配置对象,负责定义整套应用的路由树(Route Tree)。
  • GoRoute:基础路由单元,将具体的 URL 路径映射到对应的 Flutter 页面组件。
  • ShellRoute / StatefulShellRoute:用于将子路由嵌套在外层持久化的 UI 壳(Shell,例如 BottomNavigationBar 底部导航栏)中。其中 StatefulShellRoute 能够独立保留多个并行导航分支的状态。
  • Path URL Strategy(路径 URL 策略):移除 Web 端 URL 默认自带的 # 号片段,这是在各平台实现干净、规范 Deep Linking 的必备配置。

工作流:初始化应用与路由系统

请参考以下工作流,使用 go_router 初始化全新的 Flutter 项目并配置根路由机制。

任务进度

  • [ ] 创建 Flutter 项目。
  • [ ] 添加 go_router 依赖。
  • [ ] 为 Web 端 / Deep Linking 配置 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() {
  // 使用 path URL 策略,移除 Web 端的 '#' 号
  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',
    );
  }
}

工作流:配置跨平台 Deep Linking

配置各原生平台拦截特定的 URL 请求,并将其精准路由拉起进入 Flutter 应用内。

任务进度

  • [ ] 确定目标平台(iOS、Android 或两者皆有)。
  • [ ] 应用 Android 平台专属配置(Manifest + Asset Links)。
  • [ ] 应用 iOS 平台专属配置(Plist + Entitlements + AASA)。
  • [ ] 运行校验程序 -> 检查错误 -> 修复问题。

若配置 Android 平台:

  1. 修改 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>
  1. 托管 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 平台:

  1. 修改 Info.plist:开启对 Flutter 默认 Deep Link 处理器的支持。
    注意:若使用了第三方 Deep Link 插件(如 app_links),请将其设为 NO 以免发生冲突。
<key>FlutterDeepLinkingEnabled</key>
<true/>
  1. 修改 Runner.entitlements:添加关联域名(Associated Domain)。
<key>com.apple.developer.associated-domains</key>
<array>
  <string>applinks:yourdomain.com</string>
</array>
  1. 托管 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": [{"/": "/*"}]
    }]
  }
}

验证闭环(Validation Loop)

运行校验程序 -> 检查错误 -> 修复问题。

  • 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
  • [ ] 为每个导航 Tab 选项卡创建对应的 StatefulShellBranch 实例。
  • [ ] 使用 StatefulNavigationShell 实现 Shell 组件。
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(),
            ),
          ],
        ),
      ],
    ),
  ],
);

代码示例

高保真 Shell 组件实现

实现用于接收 StatefulNavigationShell 并处理 Tab 分支切换的 UI 外壳组件。

class ScaffoldWithNavBar extends StatelessWidget {
  const ScaffoldWithNavBar({
    required this.navigationShell,
    super.key,
  });

  final StatefulNavigationShell navigationShell;

  void _goBranch(int index) {
    navigationShell.goBranch(
      index,
      // 当点击当前已选中的 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() 拓展方法。

// 替换当前路由栈为目标路由(声明式导航)
context.go('/details/123');

// 将目标路由压入现有路由栈顶部(命令式导航)
context.push('/details/123');

// 使用命名路由及路径参数进行导航
context.goNamed('details', pathParameters: {'id': '123'});

// 弹出当前路由
context.pop();