# Declarative Routing With go_router — Flutter

Source: https://www.skillbyai.com/en/flutter/n-gorouter

> URL-based routes for apps and the web.

## Routes as configuration

For apps with many screens, web URLs or deep links, a declarative router maps **paths to screens**. **go_router** (a package maintained by the Flutter team) is the common choice: you declare `GoRoute`s with paths such as `/products/:id`, give the `GoRouter` to `MaterialApp.router(routerConfig: ...)`, and navigate with `context.go('/products/42')` (replace the stack to match the URL) or `context.push(...)` (add on top). Nested routes build a back stack, `ShellRoute` and `StatefulShellRoute` keep a persistent bottom navigation bar, and a `redirect` callback can send unauthenticated users to a sign-in page. go_router's API has changed across major versions, so check the docs for your version.

## A router with a path parameter

go_router configuration (API varies by version).

```dart
import 'package:go_router/go_router.dart';

final router = GoRouter(
  initialLocation: '/',
  redirect: (context, state) {
    final loggedIn = authService.isLoggedIn;
    final goingToLogin = state.matchedLocation == '/login';
    if (!loggedIn && !goingToLogin) return '/login';
    return null; // no redirect
  },
  routes: [
    GoRoute(path: '/login', builder: (context, state) => const LoginPage()),
    GoRoute(
      path: '/',
      builder: (context, state) => const HomePage(),
      routes: [
        GoRoute(
          path: 'products/:id', // child path: /products/42
          builder: (context, state) =>
              ProductPage(id: state.pathParameters['id']!),
        ),
      ],
    ),
  ],
);

// app root
MaterialApp.router(routerConfig: router);

// navigating
context.go('/products/42');
```

## go versus push

context.go makes the stack match the URL, so going "back" follows the route hierarchy; context.push stacks a page on top of the current one. Mixing them carelessly produces surprising back-button behaviour.

**Quiz:** What is a main advantage of declarative routing with go_router?

- [ ] It replaces state management
- [ ] It removes the need for widgets
- [ ] It makes apps compile faster
- [x] Screens are addressable by URL, which supports the web and deep links

*Answer:* Screens are addressable by URL, which supports the web and deep links. Paths map directly to screens, so external links can open any page.
