flutter-setup-declarative-routing

flutter-setup-declarative-routing

熱門

使用 `go_router` 等套件設定 `MaterialApp.router`,以實現進階的 URL 導航。適用於開發需要特定深度連結和瀏覽器歷史記錄支援的網頁應用程式或行動應用程式。

2525星標
152分支
更新於 2026/6/18
SKILL.md
readonlyread-only
name
flutter-setup-declarative-routing
description

使用 `go_router` 等套件設定 `MaterialApp.router`,以實現進階的 URL 導航。適用於開發需要特定深度連結和瀏覽器歷史記錄支援的網頁應用程式或行動應用程式。

實作路由與深度連結

目錄

核心概念

在 Flutter 中使用 go_router 套件進行宣告式路由。它提供了強大的 API 來處理複雜的路由情境、深度連結和巢狀導航。

  • GoRouter:定義應用程式路由樹的核心設定物件。
  • GoRoute:將 URL 路徑對應到 Flutter 畫面的標準路由。
  • ShellRoute / StatefulShellRoute:將子路由包裝在持久化的 UI 外殼中(例如 BottomNavigationBar)。StatefulShellRoute 會維護平行導航分支的狀態。
  • Path URL Strategy:移除網頁 URL 中預設的 # 片段,對於跨平台的乾淨深度連結至關重要。

工作流程:初始化應用程式與路由器

按照此工作流程,使用 go_router 引導新的 Flutter 應用程式,並設定根路由機制。

任務進度

  • [ ] 建立 Flutter 應用程式。
  • [ ] 新增 go_router 依賴。
  • [ ] 設定網頁/深度連結的 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 策略移除網頁 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-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 實作外殼小工具。
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(),
            ),
          ],
        ),
      ],
    ),
  ],
);

範例

高保真外殼小工具實作

實作使用 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();