Flutter
GoRoute
Define paths with GoRoute.
Defining a route with GoRoute
GoRoute is a single route definition in GoRouter's route list. The path parameter specifies the URL path, and the builder parameter specifies the screen to show when that path is entered. The builder has the signature (BuildContext context, GoRouterState state) and returns a Widget.
GoRoute(
path: '/ayarlar',
builder: (context, state) => AyarlarScreen(),
)
Multiple GoRoute entries
A GoRouter's routes list can contain multiple GoRoute entries. Each GoRoute has its own path and builder. When the user navigates to a URL, the corresponding builder is called.
GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomeScreen(),
),
GoRoute(
path: '/ayarlar',
builder: (context, state) => AyarlarScreen(),
),
],
);
Exercise Two-route GoRouter
Define a routes list containing two GoRoute entries. The first with path: '/' returns HomeScreen(), the second with path: '/ayarlar' returns AyarlarScreen(). Pass the 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();
}
class AyarlarScreen extends StatelessWidget {
const AyarlarScreen({super.key});
@override
Widget build(BuildContext context) => const SizedBox.shrink();
}
final routes = [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/ayarlar',
builder: (context, state) => const AyarlarScreen(),
),
];
final router = GoRouter(routes: routes);
void main() {
print(routes.length);
}
Test yourself
-
What does the builder parameter of GoRoute return?
- A Widget
- A Map
- A Future
- An int
Show answer
A Widget — The builder returns a Widget; this widget is shown on screen when the path is entered. Future is for async operations, int is a number, and Map is a data structure.
-
GoRoute path parameter
GoRoute(
____,
builder: (context, state) => AyarlarScreen(),
)
Show answer
GoRoute(
path: '/ayarlar',
builder: (context, state) => AyarlarScreen(),
)
-
GoRoute parts
- path
- URL path
- builder
- Screen builder
- routes
- Route list
- GoRouterState
- Route state object
Next lesson: context.go and push