go_router in Flutter: solved exercise
If you are searching for a go_router Flutter example, this exercise shows a modern declarative navigation setup for real apps.
Problem statement
Build two screens:
- Home,
- Detail with parameter.
Navigate using go_router and named routes.
Flutter solution
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const MyApp());
final _router = GoRouter(
routes: [
GoRoute(
path: '/',
name: 'home',
builder: (_, __) => const HomePage(),
),
GoRoute(
path: '/detail/:id',
name: 'detail',
builder: (_, state) => DetailPage(id: state.pathParameters['id']!),
),
],
);
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: _router);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => context.goNamed('detail', pathParameters: {'id': '42'}),
child: const Text('Go to detail'),
),
),
);
}
}
class DetailPage extends StatelessWidget {
final String id;
const DetailPage({super.key, required this.id});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Detail')),
body: Center(child: Text('Received ID: $id')),
);
}
}Expected result
Tapping the button on Home opens the detail screen and shows the route parameter.
Common mistakes
- Not naming routes and losing semantic navigation.
- Mixing
Navigator.pushandgo_routerinconsistently. - Skipping parameter validation for optional values.
Practical use
go_router is useful for multi-flow apps and deep linking.
Recommended next exercise
- BottomNavigationBar in Flutter: solved exercise with IndexedStack
- Named Routes in Flutter: solved navigation exercise
- Flutter API Call with http: solved REST exercise
- All Flutter exercises
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View the C book on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
FAQ
Does go_router replace classic named routes?
In many projects, yes. It simplifies declarative navigation and deep links.
Is migration from Navigator 1.0 difficult?
Not always. You can migrate flow by flow.
When is go_router worth using?
When your app has multiple routes, auth flows, and complex navigation needs.