flutter-setup-declarative-routing

flutter-setup-declarative-routing

热门

使用 `go_router` 等包配置 `MaterialApp.router`,实现高级的基于 URL 的导航。适用于需要特定深度链接和浏览器历史支持的 Web 应用或移动应用开发。

2525Star
152Fork
更新于 2026/6/18
SKILL.md
只读
名称
flutter-setup-declarative-routing
描述

使用 `go_router` 等包配置 `MaterialApp.router`,实现高级的基于 URL 的导航。适用于需要特定深度链接和浏览器历史支持的 Web 应用或移动应用开发。

实现路由与深度链接

目录

核心概念

在 Flutter 中使用 go_router 包实现声明式路由。它提供了强大的 API 来处理复杂的路由场景、深度链接和嵌套导航。

  • GoRouter:核心配置对象,定义应用的路由树。
  • GoRoute:标准路由,将 URL 路径映射到 Flutter 屏幕。
  • ShellRoute / StatefulShellRoute:将子路由包裹在持久化 UI 外壳(如 BottomNavigationBar)中。StatefulShellRoute 保持并行导航分支的状态。
  • 路径 URL 策略:从 Web URL 中移除默认的 # 片段,对于跨平台的深度链接至关重要。

工作流:初始化应用和路由器

按照以下工作流引导新的 Flutter 应用使用 go_router 并配置根路由机制。

任务进度

  • [ ] 创建 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() {
  // 使用路径 URL 策略移除 Web URL 中的 '#'
  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 配置:

  1. 修改 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>
  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 的默认深度链接处理器。
    注意:如果使用第三方深度链接插件(如 app_links),请将其设置为 NO 以避免冲突。
<key>FlutterDeepLinkingEnabled</key>
<true/>
  1. 修改 Runner.entitlements:添加关联域名。
<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": [{"/": "/*"}]
    }]
  }
}

验证循环

运行验证器 -> 检查错误 -> 修复。

  • 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,
      // 支持在点击当前标签时导航到初始位置。
      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: '主页'),
          NavigationDestination(icon: Icon(Icons.settings), label: '设置'),
        ],
      ),
    );
  }
}

程序化导航

使用 go_router 提供的 context.go()context.push() 扩展方法。

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

// 将目标路由推送到现有栈上(命令式)
context.push('/details/123');

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

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