This guide explains routing in Flutter using the go_router
package, including route types, navigation methods, error handling, and data passing.
In Flutter, a router controls navigation between screens (pages) in an app.
It decides which widget to display when the user goes to a certain path (URL-like format, e.g. /profile).
go_router simplifies Flutter navigation by:
- Supporting declarative routes
- Handling deep links and web URLs
- Making nested navigation easier
- Adding query parameters and data passing support
- Add the package to your
pubspec.yaml:
dependencies:
go_router: ^14.1.4- Create a RouterClass to define all routes:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'home_page.dart';
import 'profile_page.dart';
class RouterClass {
final router = GoRouter(
initialLocation: "/",
errorBuilder: (context, state) => Scaffold(
body: Center(child: Text("404 - Page not found")),
),
routes: [
GoRoute(
path: "/",
builder: (context, state) => HomePage(),
),
GoRoute(
path: "/profile",
builder: (context, state) => ProfilePage(),
),
],
);
}GoRoute(
path: "/about",
builder: (context, state) => AboutPage(),
),- In main.dart:
import 'package:flutter/material.dart';
import 'router_class.dart';
void main() {
final routerClass = RouterClass();
runApp(MyApp(router: routerClass.router));
}
class MyApp extends StatelessWidget {
final GoRouter router;
const MyApp({super.key, required this.router});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: router,
);
}
}ElevatedButton(
onPressed: () => GoRouter.of(context).go('/profile'),
child: Text("Go to Profile"),
)- Handled via errorBuilder in GoRouter:
errorBuilder: (context, state) => Scaffold(
body: Center(child: Text("404 - Page not found")),
),GoRoute(
path: "/profile",
builder: (context, state) => ProfilePage(),
routes: [
GoRoute(
path: "settings",
builder: (context, state) => SettingsPage(),
),
],
),- Path Parameters:
GoRoute(
path: "/user/:id",
builder: (context, state) {
final id = state.pathParameters['id']!;
return UserPage(userId: id);
},
);
Navigate:
GoRouter.of(context).go('/user/123');GoRoute(
name: 'profile',
path: "/profile",
builder: (context, state) => ProfilePage(),
),
Navigate:
GoRouter.of(context).goNamed('profile');GoRoute(
path: "/age",
builder: (context, state) {
final age = int.parse(state.uri.queryParameters['age'] ?? '0');
return AgePage(age: age);
},
);
Navigate:
GoRouter.of(context).go('/age?age=25');redirect: (context, state) {
final loggedIn = false;
if (!loggedIn) return '/login';
return null;
},// Push to a new page (keeps current page in stack)
GoRouter.of(context).push('/profile');
// Push named route
GoRouter.of(context).pushNamed('profile');- go_router makes Flutter navigation:
- Easier to manage
- Web-friendly (deep links)
- Scalable for complex apps
- Use path parameters, query parameters, and nested routes for dynamic navigation in your Flutter apps.