|
| 1 | +--- |
| 2 | +title: Routing (go_router) |
| 3 | +description: An explanation of how navigation and routing are handled in the web dashboard using go_router. |
| 4 | +--- |
| 5 | + |
| 6 | +Navigation within the web dashboard is managed by the powerful [`go_router`](https://pub.dev/packages/go_router) package. This provides a robust, URL-based routing system that is essential for a web application. |
| 7 | + |
| 8 | +Our routing configuration is centralized in the `lib/router/` directory. |
| 9 | + |
| 10 | +### `StatefulShellRoute` for Persistent Navigation |
| 11 | + |
| 12 | +The main dashboard interface, which includes the top app bar and the side navigation rail, is built using a `StatefulShellRoute`. This is a specialized route type from `go_router` that is perfect for creating scaffolded UI with persistent navigation. |
| 13 | + |
| 14 | +It allows us to define several independent navigation "branches," one for each of our main sections: |
| 15 | +- Dashboard |
| 16 | +- Content Management |
| 17 | +- App Configuration |
| 18 | + |
| 19 | +When a user navigates between these sections, `StatefulShellRoute` preserves the state of each branch, including the scroll position and any nested navigation. |
| 20 | + |
| 21 | +### Authentication and Redirects |
| 22 | + |
| 23 | +The router is tightly integrated with the `AppBloc` to handle authentication-based redirects automatically. |
| 24 | + |
| 25 | +- The `GoRouter` is configured with a `refreshListenable` that listens to changes in the authentication status from the `AppBloc`. |
| 26 | +- A `redirect` function checks the user's authentication status on every navigation change. |
| 27 | + - If an unauthenticated user tries to access any page other than the sign-in page, they are automatically redirected to `/authentication`. |
| 28 | + - If an authenticated user tries to access the sign-in page, they are automatically redirected to the main `/dashboard`. |
| 29 | + |
| 30 | +This ensures that the application's routes are always protected and that users are guided to the correct screen based on their session status. |
| 31 | + |
| 32 | +### Named Routes |
| 33 | + |
| 34 | +To prevent the use of hardcoded URL strings and to make navigation more maintainable, we use **named routes**. All route paths and names are defined as constants in the `lib/router/routes.dart` file. |
| 35 | + |
| 36 | +When navigating, we use methods like `context.goNamed('routeName')` instead of `context.go('/some/path')`. This makes the code cleaner and less prone to errors if a URL path needs to be changed in the future. |
0 commit comments