Flutter
What is GoRouter?
Build declarative navigation 2.0 with GoRouter.
What is GoRouter?
GoRouter is a package that provides declarative navigation 2.0 for Flutter. You define routes as a list; each route is a GoRoute object. You connect GoRouter to your app's navigation with MaterialApp.router.
final router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomeScreen(),
),
],
);
GoRouter automatically selects the correct screen based on the URL and works with back/forward buttons.
Connecting with MaterialApp.router
To connect GoRouter to the app you use MaterialApp.router. You pass the GoRouter object to the routerConfig parameter; this way all navigation flows through GoRouter.
MaterialApp.router(
routerConfig: router,
title: 'Uygulamam',
);
This approach replaces Navigator.push calls with GoRouter's declarative structure.
Exercise Single-route GoRouter
Define a list named routes containing one GoRoute with path: '/' and a builder returning HomeScreen(). Pass this list to GoRouter and print the route count in main.
Show example solution
import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) => const SizedBox.shrink();
}
final routes = [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
];
final router = GoRouter(routes: routes);
void main() {
print(routes.length);
}
Test yourself
-
Which navigation approach does GoRouter offer?
- Only setState-based state management
- Only sqflite database operations
- C code compilation
- Declarative navigation 2.0
Show answer
Declarative navigation 2.0 — GoRouter defines routes as a declarative list; this is the navigation 2.0 approach. State management, databases, and C compilation are not GoRouter's concern.
-
Define the GoRouter
final router = ____(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomeScreen(),
),
],
);
Show answer
final router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomeScreen(),
),
],
);
-
GoRouter parts
- GoRouter
- Declarative router
- routes
- Route list
- GoRoute
- Single route definition
- MaterialApp.router
- Connects GoRouter
Next lesson: GoRoute