Navigationintermediate
GoRouter Setup
Complete GoRouter configuration with nested routes, redirects, and route guards.
#go-router#navigation#routing
dart
| 1 | import 'package:go_router/go_router.dart'; |
| 2 | |
| 3 | final appRouter = GoRouter( |
| 4 | initialLocation: '/', |
| 5 | debugLogDiagnostics: true, |
| 6 | redirect: (context, state) { |
| 7 | final isLoggedIn = AuthService.isLoggedIn; |
| 8 | final isLoginRoute = state.matchedLocation == '/login'; |
| 9 | |
| 10 | if (!isLoggedIn && !isLoginRoute) return '/login'; |
| 11 | if (isLoggedIn && isLoginRoute) return '/'; |
| 12 | return null; |
| 13 | }, |
| 14 | routes: [ |
| 15 | GoRoute( |
| 16 | path: '/', |
| 17 | builder: (context, state) => const HomePage(), |
| 18 | ), |
| 19 | GoRoute( |
| 20 | path: '/login', |
| 21 | builder: (context, state) => const LoginPage(), |
| 22 | ), |
| 23 | ShellRoute( |
| 24 | builder: (context, state, child) => AppShell(child: child), |
| 25 | routes: [ |
| 26 | GoRoute( |
| 27 | path: '/dashboard', |
| 28 | builder: (context, state) => const DashboardPage(), |
| 29 | routes: [ |
| 30 | GoRoute( |
| 31 | path: 'settings', |
| 32 | builder: (context, state) => const SettingsPage(), |
| 33 | ), |
| 34 | ], |
| 35 | ), |
| 36 | GoRoute( |
| 37 | path: '/profile/:id', |
| 38 | builder: (context, state) { |
| 39 | final id = state.pathParameters['id']!; |
| 40 | return ProfilePage(userId: id); |
| 41 | }, |
| 42 | ), |
| 43 | ], |
| 44 | ), |
| 45 | ], |
| 46 | errorBuilder: (context, state) => ErrorPage(error: state.error), |
| 47 | ); |
| 48 | |
| 49 | // Navigation helpers |
| 50 | extension AppNavigation on BuildContext { |
| 51 | void goHome() => go('/'); |
| 52 | void goLogin() => go('/login'); |
| 53 | void goDashboard() => go('/dashboard'); |
| 54 | void goProfile(String id) => go('/profile/$id'); |
| 55 | void pushSettings() => push('/dashboard/settings'); |
| 56 | } |