go_router in Flutter: solved navigation exercise

  2 minutes

If you are searching for a go_router Flutter example, this exercise shows a modern declarative navigation setup for real apps.

Build two screens:

  • Home,
  • Detail with parameter.

Navigate using go_router and named routes.

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')),
    );
  }
}

Tapping the button on Home opens the detail screen and shows the route parameter.

  • Not naming routes and losing semantic navigation.
  • Mixing Navigator.push and go_router inconsistently.
  • Skipping parameter validation for optional values.

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

In many projects, yes. It simplifies declarative navigation and deep links.

Not always. You can migrate flow by flow.

When your app has multiple routes, auth flows, and complex navigation needs.