3. Routing

Navigating between screens with go_router

Goals of this chapter

1

Home screen

The starting point for each feature

2

Define the router

Provide go_router via Riverpod

3

Go to the detail screen

Paths with parameters

Screen structure

flowchart LR
  H["/ Home"] --> U["/users<br/>User list"]
  U --> D["/users/:userId<br/>User details"]

  • Child routes extend the parent’s path (children of /users are /users/xxx)
  • The :userId part is received as a parameter

Defining the router

lib/router/router.dart
import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/ui/home/view/home_page.dart';
import 'package:motion_app/ui/user_detail/view/user_detail_page.dart';
import 'package:motion_app/ui/user_list/view/user_list_page.dart';

part 'router.g.dart';

// Keep paths as constants to prevent typos in strings
abstract final class Routes {
  static const home = '/';
  static const users = '/users';
  static String userDetail(String userId) => '/users/$userId';
}

@Riverpod(keepAlive: true)
GoRouter router(Ref ref) {
  return GoRouter(
    initialLocation: Routes.home,
    routes: [
      GoRoute(
        path: Routes.home,
        builder: (context, state) => const HomePage(),
        routes: [
          GoRoute(
            path: 'users', // child routes have no leading /
            builder: (context, state) => const UserListPage(),
            routes: [
              GoRoute(
                path: ':userId',
                builder: (context, state) => UserDetailPage(
                  userId: state.pathParameters['userId']!,
                ),
              ),
            ],
          ),
        ],
      ),
    ],
  );
}

Wiring it into the app

  • Change MaterialApp to MaterialApp.router
  • Pass the router created with Riverpod to routerConfig
lib/app.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/router/router.dart';

class App extends ConsumerWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return MaterialApp.router(
      title: 'Motion Note',
      theme: ThemeData(colorSchemeSeed: Colors.teal),
      routerConfig: ref.watch(routerProvider),
    );
  }
}

Home screen

lib/ui/home/view/home_page.dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:motion_app/router/router.dart';

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Motion Note')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          Card(
            child: ListTile(
              leading: const Icon(Icons.people),
              title: const Text('ユーザー'),
              trailing: const Icon(Icons.chevron_right),
              onTap: () => context.push(Routes.users),
            ),
          ),
        ],
      ),
    );
  }
}

Detail screen

lib/ui/user_detail/view/user_detail_page.dart
import 'package:flutter/material.dart';

class UserDetailPage extends StatelessWidget {
  const UserDetailPage({super.key, required this.userId});

  final String userId;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('ユーザー詳細')),
      body: Center(child: Text('ID: $userId')),
    );
  }
}

From the list to the details

lib/ui/user_list/view/user_list_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/router/router.dart';
import 'package:motion_app/ui/user_list/view_model/user_list_view_model.dart';

class UserListPage extends HookConsumerWidget {
  const UserListPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(userListViewModelProvider);
    final notifier = ref.read(userListViewModelProvider.notifier);
    final nameController = useTextEditingController();

    return Scaffold(
      appBar: AppBar(title: const Text('ユーザー一覧')),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: nameController,
                    decoration: InputDecoration(
                      labelText: '名前',
                      errorText: state.errorMessage,
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                FilledButton(
                  onPressed: () {
                    if (notifier.addUser(nameController.text)) {
                      nameController.clear();
                    }
                  },
                  child: const Text('追加'),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView(
              children: [
                for (final (i, name) in state.names.indexed)
                  ListTile(
                    leading: const Icon(Icons.person),
                    title: Text(name),
                    onTap: () => context.push(Routes.userDetail('$i')),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
  • .indexed yields the position (i) together with the name, and the number is passed as the ID (replaced with a real ID in Chapter 5)

Choosing a navigation method

What you want Code
Go forward (back button returns) context.push(Routes.users)
Switch screens (replace history) context.go(Routes.home)
Go back context.pop()
Receive a return value await context.push<bool>(...) / context.pop(true)

Navigate in the View

Don’t pass BuildContext or the router to the ViewModel. The ViewModel only returns results; the View performs navigation.

Checkpoint

CHECK 0 / 3