What is the key difference between context.go() and context.push() in GoRouter?
context.go() navigates by URI path updating the route tree, while context.push() imperatively pushes a route on top of the current screen.
Build production-grade declarative routing with GoRouter, path params, auth guards, and ShellRoute
Passing the Quiz & Exercises is mandatory to earn FX and proceed. If you fail, try again to gain the required FX, then the Proceed button will become available.
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
Having trouble? AI is here to help
Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.
Use the AI button at the bottom of the screen
Navigation in Flutter has evolved through two distinct eras:
Navigator.push(context, MaterialPageRoute(...))). Simple, but struggles with deep links, browser back/forward buttons, and nested bottom navigation.GoRouter is the officially recommended routing package maintained by the Flutter team. In this lesson, we will build a complete production routing system with path parameters, auth guards, and persistent bottom tabs.
First, ensure go_router is added to your pubspec.yaml. Then, initialize GoRouter as a top-level or singleton instance and wire it into MaterialApp.router.
final appRouter = GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/details',
builder: (context, state) => const DetailsScreen(),
),
],
);
// In main.dart:
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: appRouter,
);
}
}
context.go() vs context.push()context.go('/details'): Replaces the navigation hierarchy based on the target URL path. Ideal for deep links and web navigation.context.push('/details'): Pushes a new screen directly on top of the current screen stack, creating a back button regardless of URI hierarchy.Real apps pass dynamic IDs (e.g., /products/42) and filter queries (e.g., /search?query=shoes).
GoRoute(
path: '/product/:id',
builder: (context, state) {
// 1. Extract path parameter (:id)
final productId = state.pathParameters['id']!;
// 2. Extract query parameter (?ref=promo)
final referralCode = state.uri.queryParameters['ref'];
return ProductDetailScreen(
id: productId,
referralCode: referralCode,
);
},
);
// To navigate:
context.go('/product/101?ref=summer_sale');
Path parameters defined with :name are guaranteed to match when the route resolves. Query parameters, however, may be omitted by the user, so always handle queryParameters as nullable.
A classic mobile requirement is a BottomNavigationBar where each tab maintains its own navigation history and scroll position when switching tabs.
GoRouter provides StatefulShellRoute.indexedStack specifically for this pattern:
1final router = GoRouter(2initialLocation: '/home',3routes: [4StatefulShellRoute.indexedStack(5builder: (context, state, navigationShell) {6// Return your Scaffold holding the BottomNavigationBar7return Scaffold(8body: navigationShell, // Active branch widget9bottomNavigationBar: BottomNavigationBar(10currentIndex: navigationShell.currentIndex,11onTap: (index) => navigationShell.goBranch(12index,13initialLocation: index == navigationShell.currentIndex,14),15items: const [16BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),17BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),18],19),20);21},22branches: [23// Tab 1 Branch24StatefulShellBranch(25routes: [26GoRoute(path: '/home', builder: (_, __) => const HomeScreen()),27],28),29// Tab 2 Branch30StatefulShellBranch(31routes: [32GoRoute(path: '/profile', builder: (_, __) => const ProfileScreen()),33],34),35],36),37],38);
Prevent unauthorized users from accessing protected screens using redirect:
final appRouter = GoRouter(
redirect: (context, state) {
final bool isLoggedIn = AuthService.instance.isLoggedIn;
final bool isLoggingIn = state.matchedLocation == '/login';
// If user is not logged in and not on login screen, redirect to login
if (!isLoggedIn && !isLoggingIn) return '/login';
// If user is already logged in and navigates to login, redirect to home
if (isLoggedIn && isLoggingIn) return '/home';
// Return null to continue to requested destination
return null;
},
routes: [ /* ... */ ],
);
Always check if the user is already on the target route (e.g., state.matchedLocation == '/login') before returning a redirect string. Failing to check causes infinite navigation loop exceptions.
Build production grade declarative routing with GoRouter, path params, auth guards, and ShellRoute. Navigation manages how users move between screens and return to previous states.
Connect each concept to real app features you can build.
Design route names and arguments before wiring screen UI.
Poor routing decisions create confusing UX and fragile deep-link behavior.
context.go() navigates by URI path updating the route tree, while context.push() imperatively pushes a route on top of the current screen.
StatefulShellRoute.indexedStack creates independent branch navigators for each tab, preserving state and scroll positions when switching.
GoRouter provides matched path parameters as a map inside state.pathParameters.
Returning null tells GoRouter to allow the navigation to proceed to the requested target destination without interception.
Something seems incorrect, unclear, or missing? Let us know.
FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.
Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.
Sign in to continue with exercises and quiz for this lesson.
Sign In to Continue