go_router in Flutter: solved navigation exercise

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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.push and go_router inconsistently.
  • Skipping parameter validation for optional values.

Practical use

go_router is useful for multi-flow apps and deep linking.

Guided practice and next step

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.