D
NavigationEasy20 XP4 min read

How do you set up and use go_router in a Flutter app?

TL;DR: Define a GoRouter with a list of GoRoutes. Replace MaterialApp with MaterialApp.router. Navigate with context.go() (replace) or context.push() (stack). Pass parameters via path params or extras.

Full Answer

go_router is Google's official, declarative routing package built on Navigator 2.0. It handles deep linking, URL parameters, redirects, and nested navigation.

  • GoRoute(path, builder) — maps a URL path to a widget
  • context.go('/path') — navigate, replacing history (like replaceNamed)
  • context.push('/path') — push onto stack, back button works
  • context.pop() — go back
  • state.pathParameters — access :param values from the URL
  • state.extra — pass arbitrary Dart objects (not URL-safe)
  • redirect — global or route-level redirect for auth guards
🎯

Use GoRouterState.extra for passing complex objects (e.g., full model objects) between routes. Use path/query parameters for shareable, deep-linkable state.

Code Examples

dartFull go_router setup
Output
Unauthenticated users are redirected to /login; authenticated users can navigate to / and /product/:id

Common Mistakes

  • Using context.go() when you want a back button — use context.push() for stack navigation
  • Passing objects via path parameters — use state.extra for complex objects

Interview Tip

💡

Showing the redirect pattern for auth guards is a strong answer — it covers the most common real-world routing requirement.

#go_router#GoRouter#GoRoute#navigation