GoRouter 고급 튜토리얼 2026: Bottom Nav, Nested Routes, Auth Redirects & Typed Navigation 🚀

발행: (2026년 2월 9일 오전 03:35 GMT+9)
3 분 소요
원문: Dev.to

Source: Dev.to

소개

다양한 페이지에서 하단 네비게이션 바를 지속시키는 것은 예전에는 어려운 일이었습니다. GoRouter(와 약간의 Riverpod)를 사용하면 딥링크, 중첩 라우트, 지속 가능한 하단 네비게이션 쉘, 그리고 타입이 지정된 네비게이션 헬퍼를 구현할 수 있습니다.

의존성 추가

dependencies:
  go_router: ^17.1.0
  flutter_riverpod: ^2.6.1

dev_dependencies:
  build_runner: ^2.6.0
  go_router_builder: ^4.0.1

타입이 지정된 헬퍼를 만들기 위해 코드 생성기를 실행합니다:

dart run build_runner build

라우터 설정 (lib/router/app_router.dart)

import 'package:go_router/go_router.dart';
import 'package:flutter/material.dart';

// Typed route data example
part 'app_router.g.dart';

@TypedGoRoute(path: '/')
class HomeRoute extends GoRouteData {
  @override
  Widget build(BuildContext context, GoRouterState state) => const HomeScreen();
}

@TypedGoRoute(path: '/details/:id')
class DetailsRoute extends GoRouteData {
  final String id;
  DetailsRoute(this.id);
  @override
  Widget build(BuildContext context, GoRouterState state) =>
      DetailsScreen(id: id);
}

// Shell for bottom navigation
final _rootNavigatorKey = GlobalKey();
final _shellNavigatorKey = GlobalKey();

final router = GoRouter(
  navigatorKey: _rootNavigatorKey,
  initialLocation: '/',
  redirect: (context, state) {
    // Riverpod auth check example
    final isLoggedIn = false; // replace with ref.watch(authProvider)
    if (!isLoggedIn && state.uri.toString() != '/login') {
      return '/login';
    }
    return null;
  },
  routes: [
    ShellRoute(
      builder: (context, state, child) => ScaffoldWithNavBar(child: child),
      routes: [
        GoRoute(
          path: '/',
          builder: (context, state) => const HomeScreen(),
          routes: [
            GoRoute(
              path: 'details/:id',
              builder: (context, state) => DetailsScreen(
                id: state.pathParameters['id']!,
              ),
            ),
          ],
        ),
        GoRoute(
          path: '/profile',
          builder: (_, __) => const ProfileScreen(),
        ),
        GoRoute(
          path: '/settings',
          builder: (_, __) => const SettingsScreen(),
        ),
      ],
    ),
    GoRoute(
      path: '/login',
      builder: (_, __) => const LoginScreen(),
    ),
  ],
  errorBuilder: (context, state) => ErrorScreen(state.error),
);

하단‑네비게이션 쉘

ShellRoute(또는 StatefulShellRoute.indexedStack)는 각 탭(홈, 프로필, 설정)의 상태를 유지하면서 각 브랜치 내부에서 네비게이션을 할 수 있게 해줍니다.

메인 엔트리 (main.dart)

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'router/app_router.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return MaterialApp.router(
      title: 'Advanced GoRouter Tutorial',
      theme: ThemeData(
        useMaterial3: true,
        colorSchemeSeed: Colors.blue,
      ),
      routerConfig: router,
    );
  }
}

네비게이션

  • 명령형 네비게이션:

    context.go('/details/123');
  • 타입이 지정된 네비게이션(생성된 헬퍼):

    DetailsRoute(id: '123').go(context);

전체 소스 코드

전체 프로젝트는 GitHub에서 확인할 수 있습니다:

https://github.com/techwithsam/gorouter_tutorial

Back to Blog

관련 글

더 보기 »