Flutter
Summary - GoRouter
Combine GoRouter and GoRoute to make a three-screen flow.
Three-screen flow
A three-screen flow: you define three GoRoute entries in GoRouter's routes list. You switch between screens with context.go and read path parameters with state.pathParameters. You connect the router to the app with MaterialApp.router.
final router = GoRouter(
routes: [
GoRoute(path: '/', builder: (c, s) => HomeScreen()),
GoRoute(path: '/liste', builder: (c, s) => ListeScreen()),
GoRoute(path: '/detay/:id', builder: (c, s) {
final id = s.pathParameters['id']!;
return DetayScreen(id: id);
}),
],
);
Exercise Three-screen GoRouter
Define a routes list containing three GoRoute entries. The first with '/' returns HomeScreen(), the second with '/liste' returns ListeScreen(), the third with '/detay/:id' returns DetayScreen(id: id) (read id from state.pathParameters['id']). 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 ListeScreen extends StatelessWidget {
const ListeScreen({super.key});
@override
Widget build(BuildContext context) => const SizedBox.shrink();
}
class DetayScreen extends StatelessWidget {
final String id;
const DetayScreen({super.key, required this.id});
@override
Widget build(BuildContext context) => const SizedBox.shrink();
}
final routes = [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/liste',
builder: (context, state) => const ListeScreen(),
),
GoRoute(
path: '/detay/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
return DetayScreen(id: id);
},
),
];
final router = GoRouter(routes: routes);
void main() {
print(routes.length);
}
Test yourself
-
Which parts work together in a three-screen flow?
- Provider + ChangeNotifier + setState
- GoRouter + GoRoute + context.go
- Column + Row + Padding
- sqflite + http + FutureBuilder
Show answer
GoRouter + GoRoute + context.go — GoRouter defines routes, GoRoute specifies each path, and context.go switches between screens. The other options concern database/network, state management, and layout; they are not part of the GoRouter flow.
-
Connect GoRouter to MaterialApp.router
MaterialApp.router(
routerConfig: ____,
title: 'Uygulama',
);
Show answer
MaterialApp.router(
routerConfig: router,
title: 'Uygulama',
);
-
Summary parts
- GoRouter
- The router
- GoRoute
- Route definition
- context.go
- Screen switching
- state.pathParameters
- Path parameters
Next lesson: What is a custom widget?