← 返回 Skills 市场
tobiasbentin

Go Router

作者 tobiasbentin · GitHub ↗ · v1.0.0
cross-platform ✓ 安全检测通过
295
总下载
0
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install go-router
功能描述
Declarative URL-based routing for Flutter using the Router API. Use when implementing navigation between screens, deep links, authentication guards, paramete...
使用说明 (SKILL.md)

Go Router

GoRouter is a declarative routing package for Flutter that uses the Router API to provide convenient URL-based navigation.

Core Concepts

1. Router Configuration

Define routes as a list of GoRoute objects:

final GoRouter _router = GoRouter(
  initialLocation: '/',
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const HomeScreen(),
    ),
    GoRoute(
      path: '/user/:id',
      builder: (context, state) {
        final userId = state.pathParameters['id']!;
        return UserScreen(id: userId);
      },
    ),
  ],
);

2. Navigation

// Simple navigation
context.go('/details');

// With parameters
context.go('/user/123');

// Named navigation (requires name parameter)
context.goNamed('user', pathParameters: {'id': '123'});

// Push (adds to stack)
context.push('/modal');

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

// Go back
context.pop();

// With query parameters
context.go('/search?q=flutter');

3. Route Parameters

Path parameters use : prefix:

GoRoute(
  path: '/user/:id/posts/:postId',
  builder: (context, state) {
    final userId = state.pathParameters['id']!;
    final postId = state.pathParameters['postId']!;
    return PostScreen(userId: userId, postId: postId);
  },
)

Query parameters are accessed via state.uri.queryParameters:

GoRoute(
  path: '/search',
  builder: (context, state) {
    final query = state.uri.queryParameters['q'] ?? '';
    return SearchScreen(query: query);
  },
)

Common Patterns

Pattern 1: Authentication Guard with Redirection

final routerProvider = Provider\x3CGoRouter>((ref) {
  final auth = ref.watch(authProvider);
  
  return GoRouter(
    initialLocation: '/',
    redirect: (context, state) {
      final isLoggedIn = auth.isLoggedIn;
      final isAuthRoute = state.matchedLocation == '/login';
      
      if (!isLoggedIn && !isAuthRoute) {
        return '/login';
      }
      if (isLoggedIn && isAuthRoute) {
        return '/';
      }
      return null;
    },
    routes: [
      GoRoute(path: '/login', builder: (_, __) => const LoginScreen()),
      GoRoute(path: '/', builder: (_, __) => const HomeScreen()),
    ],
  );
});

Pattern 2: ShellRoute for Bottom Navigation

GoRouter(
  routes: [
    ShellRoute(
      builder: (context, state, child) {
        return ScaffoldWithNavBar(child: child);
      },
      routes: [
        GoRoute(
          path: '/',
          builder: (_, __) => const HomeScreen(),
        ),
        GoRoute(
          path: '/settings',
          builder: (_, __) => const SettingsScreen(),
        ),
      ],
    ),
  ],
)

Pattern 3: StatefulShellRoute for Nested Navigation

StatefulShellRoute(
  branches: [
    StatefulShellBranch(
      routes: [GoRoute(path: '/feed', builder: (_, __) => FeedScreen())],
    ),
    StatefulShellBranch(
      routes: [GoRoute(path: '/profile', builder: (_, __) => ProfileScreen())],
    ),
  ],
)

Pattern 4: Custom Page Transitions

GoRoute(
  path: '/details',
  pageBuilder: (context, state) => const MaterialPage(
    child: DetailsScreen(),
  ),
  // Or custom transition
  pageBuilder: (context, state) => CustomTransitionPage(
    child: const DetailsScreen(),
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      return FadeTransition(
        opacity: CurveTween(curve: Curves.easeInOut).animate(animation),
        child: child,
      );
    },
  ),
)

Pattern 5: Error Handling

GoRouter(
  errorBuilder: (context, state) {
    return ErrorScreen(error: state.error);
  },
  // Or handle 404
  errorPageBuilder: (context, state) => MaterialPage(
    child: NotFoundScreen(path: state.uri.path),
  ),
)

Pattern 6: Type-Safe Routes (Go Router 14+)

Define typed routes:

part 'app_routes.g.dart';

@TypedGoRoute\x3CHomeRoute>(path: '/')
class HomeRoute extends GoRouteData {
  @override
  Widget build(BuildContext context, GoRouterState state) {
    return const HomeScreen();
  }
}

@TypedGoRoute\x3CUserRoute>(path: '/user/:id')
class UserRoute extends GoRouteData {
  final String id;
  const UserRoute({required this.id});
  
  @override
  Widget build(BuildContext context, GoRouterState state) {
    return UserScreen(id: id);
  }
}

Route State

Access route information in builders:

GoRoute(
  path: '/details',
  builder: (context, state) {
    // Path: state.uri.path
    // Query params: state.uri.queryParameters
    // Extra data: state.extra (passed via context.go('/details', extra: data))
    return DetailsScreen(
      path: state.uri.path,
      data: state.extra as MyData?,
    );
  },
)

Navigation Helper Methods

// Extension for cleaner navigation
extension NavigationHelpers on BuildContext {
  void goHome() => go('/');
  void goUser(String id) => go('/user/$id');
  void pushModal(Widget screen) => push('/modal', extra: screen);
}

// Usage
context.goHome();
context.goUser('123');

Web Support

Enable web URL handling:

GoRouter(
  // Handles browser back/forward
  // URL updates automatically
  initialLocation: '/',
  // For base href in web
  routerNeglect: true, // Disable browser history
)

// Access current route
final currentRoute = GoRouter.of(context).routeInformationProvider.value.uri.path;

Route Observers

GoRouter(
  observers: [RouteObserver()],
  navigatorBuilder: (context, state, child) {
    // Wrap all routes
    return SomeWrapper(child: child);
  },
)

Testing

testWidgets('navigates correctly', (tester) async {
  await tester.pumpWidget(
    MaterialApp.router(
      routerConfig: _router,
    ),
  );
  
  // Find and tap button
  await tester.tap(find.text('Go to details'));
  await tester.pumpAndSettle();
  
  // Verify navigation
  expect(find.text('Details'), findsOneWidget);
});

Code Generation

For type-safe routes with code generation:

dart run build_runner build

Generates:

  • $route constant for route location
  • Parameter classes for typed routes

Deep Linking

Configure Android & iOS for deep links, then handle in GoRouter:

GoRouter(
  routes: [
    GoRoute(
      path: '/product/:id',
      builder: (context, state) {
        // Handles myapp.com/product/123
        // and app://product/123
        return ProductScreen(id: state.pathParameters['id']!);
      },
    ),
  ],
)

Navigation Without Context

// Store router reference
final GoRouter router = GoRouter(...);

// Navigate without context
router.go('/home');
router.push('/modal');
router.pop();

See BEST_PRACTICES.md for architecture patterns.

安全使用建议
This skill is documentation and code examples for using GoRouter in Flutter; it doesn't ask for credentials, install binaries, or access your system. That said, the skill's source and homepage are unknown — if you plan to rely on this content in production, cross-check against the official go_router package documentation on pub.dev or the project's repository to ensure examples match the current library version and licensing. If you prefer maximum assurance, obtain routing code from the official package or a trusted repository rather than an undocumented skill bundle.
功能分析
Type: OpenClaw Skill Name: go-router Version: 1.0.0 The skill bundle describes the 'GoRouter' Flutter package, providing documentation and Dart code examples for declarative URL-based navigation. All files (`_meta.json`, `SKILL.md`, `BEST_PRACTICES.md`) contain only informational text and client-side Dart code snippets relevant to Flutter application development. There is no evidence of malicious intent, such as data exfiltration, unauthorized command execution, persistence mechanisms, obfuscation, or prompt injection attempts against the AI agent. The instructions are purely descriptive and do not attempt to manipulate the agent's behavior or access sensitive resources.
能力评估
Purpose & Capability
The name/description (Go Router for Flutter) aligns with the SKILL.md and BEST_PRACTICES.md contents, which are code examples and patterns for GoRouter usage. Nothing requested or described is disproportionate to a routing helper.
Instruction Scope
Runtime instructions are purely examples and guidance (Dart/Flutter code snippets). They do not instruct reading system files, environment variables, network exfiltration, or contacting external endpoints outside normal package usage.
Install Mechanism
No install spec or code files that would write/execute artifacts are present. This is an instruction-only skill (lowest install risk).
Credentials
The skill declares no required environment variables, credentials, or config paths; the instructions do not reference secrets or other environment data.
Persistence & Privilege
always is false and the skill does not request persistent system presence or modify other skills/settings. Autonomous invocation is allowed (platform default) but does not increase risk given the skill's read-only, documentation nature.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install go-router
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /go-router 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
- Initial release of the go-router skill for Flutter. - Provides declarative, URL-based routing using the Router API. - Covers navigation, deep linking, authentication guards, parameterized and nested routes, shell routes, and web routing. - Includes practical Flutter code examples and common routing patterns. - Highlights type-safe routes, route state, page transitions, error handling, and integration for testing and deep links.
元数据
Slug go-router
版本 1.0.0
许可证
累计安装 0
当前安装数 0
历史版本数 1
常见问题

Go Router 是什么?

Declarative URL-based routing for Flutter using the Router API. Use when implementing navigation between screens, deep links, authentication guards, paramete... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 295 次。

如何安装 Go Router?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install go-router」即可一键安装,无需额外配置。

Go Router 是免费的吗?

是的,Go Router 完全免费(开源免费),可自由下载、安装和使用。

Go Router 支持哪些平台?

Go Router 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Go Router?

由 tobiasbentin(@tobiasbentin)开发并维护,当前版本 v1.0.0。

💬 留言讨论