Flutter导航

Mattakushi4322026-10-25查看 1295复制 1433

何时激活:Flutter 导航、GoRouter、Navigator 2.0、深层链接、shell 路由、重定向、路由、go_router

Download (.md)

📘如何使用这个技能

  1. 1
    复制技能内容·点击上方「Copy SKILL.md」复制全部内容,或 Download 下载到本地
  2. 2
    打开你的 AI 客户端·支持 Claude Code、Trae、Cursor、ChatGPT、DeepSeek、Kimi 等任意 AI 助手
  3. 3
    粘贴为系统提示/知识文件·Claude Code:放入 .claude/skills/ 目录;普通对话:作为首条消息发送并说「请严格按这份技能文档执行」
  4. 4
    直接提出你的需求·AI 会按技能定义的工作流、格式和约束来处理,无需再解释背景

💡 提示:技能生效后,每次对话只需一句需求,AI 会按 SKILL.md 的流程执行。

SKILL.md4840 chars
---
name: flutter-navigation
description: "When to activate: Flutter navigation, GoRouter, Navigator 2.0, deep linking, shell routes, redirects, routing, go_router"
origin: zakr
metadata:
  namespace: zakr/devtools-pack
  version: 1.0.0
  category: engineering
  language: dart
  platforms: [claude-code, codex, gemini-cli, cursor, aider, windsurf]
---
# Flutter Navigation Patterns

## GoRouter Setup

```dart
// lib/router.dart
final routerProvider = Provider<GoRouter>((ref) {
  final authState = ref.watch(authProvider);

  return GoRouter(
    initialLocation: '/home',
    redirect: (context, state) {
      final isLoggedIn = authState == AuthState.authenticated;
      final isAuthRoute = state.matchedLocation.startsWith('/auth');
      if (!isLoggedIn && !isAuthRoute) return '/auth/login';
      if (isLoggedIn && isAuthRoute) return '/home';
      return null;
    },
    routes: [
      GoRoute(path: '/auth/login', builder: (_, __) => const LoginPage()),
      ShellRoute(
        builder: (context, state, child) => AppShell(child: child),
        routes: [
          GoRoute(
            path: '/home',
            builder: (_, __) => const HomePage(),
          ),
          GoRoute(
            path: '/profile/:userId',
            builder: (_, state) => ProfilePage(userId: state.pathParameters['userId']!),
            routes: [
              GoRoute(
                path: 'edit',
                builder: (_, state) => EditProfilePage(userId: state.pathParameters['userId']!),
              ),
            ],
          ),
        ],
      ),
    ],
  );
});
```

## Programmatic Navigation

```dart
// Push (stack)
context.push('/profile/123');

// Replace current route
context.replace('/home');

// Go (clear stack to route)
context.go('/home');

// Pop
context.pop();

// Pop with result
context.pop({'saved': true});

// Push and await result
final result = await context.push<Map<String, dynamic>>('/settings');
if (result?['saved'] == true) { ... }
```

## Route Parameters

```dart
GoRoute(
  path: '/product/:id',
  builder: (context, state) {
    final id = state.pathParameters['id']!;              // /product/42
    final tab = state.uri.queryParameters['tab'] ?? 'info'; // ?tab=reviews
    final extra = state.extra as Product?;              // passed via context.push extra
    return ProductPage(id: id, tab: tab, product: extra);
  },
),

// Navigate with extra data (not URL-serialized)
context.push('/product/42', extra: product);
```

## ShellRoute for Persistent Bottom Nav

```dart
ShellRoute(
  builder: (context, state, child) {
    return Scaffold(
      body: child,
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex(state.uri.toString()),
        onTap: (i) => context.go(_tabs[i]),
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
          BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
        ],
      ),
    );
  },
  routes: [
    GoRoute(path: '/home', builder: ...),
    GoRoute(path: '/search', builder: ...),
    GoRoute(path: '/profile', builder: ...),
  ],
),
```

## Deep Linking Configuration

```yaml
# android/app/src/main/AndroidManifest.xml intent-filter
# Add inside <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="https" android:host="myapp.example.com" />
# </intent-filter>
```

```dart
// GoRouter handles deep links automatically when paths match
GoRouter(
  routes: [
    GoRoute(path: '/share/:code', builder: (_, state) =>
      SharePage(code: state.pathParameters['code']!)),
  ],
);
// https://myapp.example.com/share/ABC123 → SharePage(code: 'ABC123')
```

## Nested Navigation (per-tab history)

```dart
// Use StatefulShellRoute for independent navigation stacks per tab
StatefulShellRoute.indexedStack(
  builder: (context, state, navigationShell) {
    return ScaffoldWithNavBar(navigationShell: navigationShell);
  },
  branches: [
    StatefulShellBranch(routes: [GoRoute(path: '/home', builder: ...)]),
    StatefulShellBranch(routes: [GoRoute(path: '/search', builder: ...)]),
  ],
),
```

## Error and Loading Routes

```dart
GoRouter(
  errorBuilder: (context, state) => ErrorPage(error: state.error),
  routes: [...],
);
```

## Testing Routes

```dart
testWidgets('navigates to profile', (tester) async {
  final router = GoRouter(routes: appRoutes);
  await tester.pumpWidget(MaterialApp.router(routerConfig: router));

  router.push('/profile/1');
  await tester.pumpAndSettle();

  expect(find.byType(ProfilePage), findsOneWidget);
});
```
来源:skillsdirectory

评论0

登录后参与评论

还没有评论,来抢沙发吧