go_router는 Flutter 앱에서 권장하는 라우팅 패키지예요. 딥 링킹을 기본으로 지원해요. URL 패턴으로 라우트를 정의하면 go_router가 들어오는 딥 링크를 알맞은 화면에 자동으로 연결해요. 이 가이드에서는 실서비스에서 딥 링킹에 필요한 라우팅 패턴을 다뤄요.
플랫폼 수준 설정(Associated Domains, 인텐트 필터)은 Flutter 딥 링킹 완전 설정 튜토리얼을 참고하세요. 크로스 플랫폼 개요는 크로스 플랫폼 딥 링킹 가이드.
기본 라우트 설정
go_router 설치
# pubspec.yaml
dependencies:
go_router: ^14.0.0
라우트 정의
final GoRouter router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/product/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
return ProductScreen(id: id);
},
),
GoRoute(
path: '/category/:slug',
builder: (context, state) {
final slug = state.pathParameters['slug']!;
return CategoryScreen(slug: slug);
},
),
GoRoute(
path: '/invite/:code',
builder: (context, state) {
final code = state.pathParameters['code']!;
return InviteScreen(code: code);
},
),
],
errorBuilder: (context, state) => const NotFoundScreen(),
);
MaterialApp과 함께 사용
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: router,
);
}
}
OS가 다음과 같은 딥 링크를 전달하면 https://go.yourapp.com/product/456, go_router는 스킴과 호스트를 떼어 내고 경로를 라우트에 매칭해요 /product/456 라우트 패턴과 비교해서 아래 화면을 렌더링해요: ProductScreen(id: "456").
중첩 라우트
지속되는 UI를 위한 ShellRoute
대부분의 앱에는 화면이 바뀌어도 유지되는 하단 내비게이션 바가 있어요. 이때 ShellRoute 를 사용하면 딥 링크로 안쪽 콘텐츠를 이동해도 스캐폴드가 유지돼요:
final router = GoRouter(
routes: [
ShellRoute(
builder: (context, state, child) {
return ScaffoldWithBottomNav(child: child);
},
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'product/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
return ProductScreen(id: id);
},
),
],
),
GoRoute(
path: '/search',
builder: (context, state) => const SearchScreen(),
routes: [
GoRoute(
path: 'results',
builder: (context, state) {
final query = state.uri.queryParameters['q'] ?? '';
return SearchResultsScreen(query: query);
},
),
],
),
GoRoute(
path: '/profile',
builder: (context, state) => const ProfileScreen(),
),
],
),
],
);
딥 링크 /product/123 ScaffoldWithBottomNav 안에 ProductScreen이 표시되고 홈 탭이 선택돼요. 딥 링크 /search/results?q=shoes 로 이동하면 SearchResultsScreen이 표시되고 검색 탭이 선택돼요.
탭 상태 보존을 위한 StatefulShellRoute
각 탭이 자기만의 내비게이션 상태를 유지하게 하려면(탭을 바꿔도 스택이 초기화되지 않도록) 이렇게 하세요:
final router = GoRouter(
routes: [
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) {
return ScaffoldWithBottomNav(navigationShell: navigationShell);
},
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'product/:id',
builder: (context, state) {
return ProductScreen(id: state.pathParameters['id']!);
},
),
],
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/search',
builder: (context, state) => const SearchScreen(),
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/profile',
builder: (context, state) => const ProfileScreen(),
),
],
),
],
),
],
);
쿼리 파라미터
쿼리 파라미터는 다음 객체로 읽어요: state.uri.queryParameters:
GoRoute(
path: '/search',
builder: (context, state) {
final query = state.uri.queryParameters['q'] ?? '';
final sort = state.uri.queryParameters['sort'] ?? 'relevance';
final page = int.tryParse(state.uri.queryParameters['page'] ?? '1') ?? 1;
return SearchScreen(query: query, sort: sort, page: page);
},
),
URL: https://go.yourapp.com/search?q=shoes&sort=price&page=2
리다이렉트와 인증 가드
딥 링크는 로그인이 필요한 화면을 가리키는 경우가 많아요. go_router의 redirect 기능이 있어요: 함수로 이 문제를 해결할 수 있어요:
final router = GoRouter(
redirect: (context, state) {
final isLoggedIn = authService.isLoggedIn;
final isLoginRoute = state.matchedLocation == '/login';
// If not logged in and not already on login, redirect to login
if (isLoggedIn == false && isLoginRoute == false) {
// Save the intended destination for after login
return '/login?redirect=${Uri.encodeComponent(state.uri.toString())}';
}
// If logged in and on login page, redirect to home
if (isLoggedIn && isLoginRoute) {
return '/';
}
return null; // No redirect
},
routes: [
GoRoute(
path: '/login',
builder: (context, state) {
final redirect = state.uri.queryParameters['redirect'];
return LoginScreen(redirectAfterLogin: redirect);
},
),
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/product/:id',
builder: (context, state) {
return ProductScreen(id: state.pathParameters['id']!);
},
),
],
);
로그인 후에는 저장해 둔 리디렉션 URL로 이동하세요:
class LoginScreen extends StatelessWidget {
final String? redirectAfterLogin;
const LoginScreen({this.redirectAfterLogin});
void onLoginSuccess(BuildContext context) {
if (redirectAfterLogin != null) {
context.go(Uri.decodeComponent(redirectAfterLogin!));
} else {
context.go('/');
}
}
}
이렇게 하면 https://go.yourapp.com/product/123 로그인하지 않은 사용자에게는 로그인 화면이 보이고, 로그인 후에는 자동으로 상품 화면으로 이동해요.
라우트 단위 리다이렉트
전역이 아니라 특정 라우트에만 적용할 리디렉션은 이렇게 작성해요:
GoRoute(
path: '/admin',
redirect: (context, state) {
if (authService.isAdmin == false) {
return '/'; // Non-admins redirected to home
}
return null;
},
builder: (context, state) => const AdminScreen(),
),
레거시 URL 처리
다른 플랫폼에서 옮겨오는 중이라면 기존 링크의 URL 패턴이 다를 수 있어요. 레거시 경로는 리디렉션으로 처리하세요:
final router = GoRouter(
redirect: (context, state) {
final path = state.matchedLocation;
// Legacy: /item/123 → /product/123
if (path.startsWith('/item/')) {
return path.replaceFirst('/item/', '/product/');
}
// Legacy: /p?id=123 → /product/123
if (path == '/p') {
final id = state.uri.queryParameters['id'];
if (id != null) return '/product/$id';
}
return null;
},
routes: [
// Current routes...
],
);
추가 데이터를 쓰는 타입 안전 라우트
go_router는 URL 파라미터와 함께 타입이 있는 데이터를 넘기는 것도 지원해요:
GoRoute(
path: '/product/:id',
builder: (context, state) {
// URL parameter (always a string)
final id = state.pathParameters['id']!;
// Extra data passed programmatically (not from URL)
final product = state.extra as Product?;
return ProductScreen(id: id, preloadedProduct: product);
},
),
앱 안에서 이동할 때는 객체 전체를 넘길 수 있어요:
context.go('/product/123', extra: product);
딥 링크로 들어오면 state.extra 는 null이에요. 그러면 화면이 URL의 ID로 상품을 가져와요. 이 패턴이면 앱 안 이동은 다시 불러오지 않아 빠르고, 딥 링크도 올바로 처리돼요.
오류 처리
커스텀 에러 화면
final router = GoRouter(
errorBuilder: (context, state) {
return ErrorScreen(
message: 'Page not found: ${state.uri.path}',
);
},
routes: [
// ...
],
);
잘못된 파라미터 처리
라우트 빌더에서 파라미터를 검증하세요:
GoRoute(
path: '/product/:id',
builder: (context, state) {
final idStr = state.pathParameters['id'];
final id = int.tryParse(idStr ?? '');
if (id == null) {
return const NotFoundScreen();
}
return ProductScreen(id: id);
},
),
디버깅
진단 로그를 켜세요:
final router = GoRouter(
debugLogDiagnostics: true,
routes: [
// ...
],
);
그러면 콘솔에 이런 로그가 출력돼요:
GoRouter: setting initial location /
GoRouter: Using MaterialApp configuration
GoRouter: going to /product/123
GoRouter: pushing /product/123
라우트 테스트
라우트 설정을 테스트하세요:
import 'package:flutter_test/flutter_test.dart';
void main() {
test('product route matches /product/:id', () {
final match = router.configuration.findMatch('/product/123');
expect(match.uri.path, '/product/123');
expect(match.pathParameters['id'], '123');
});
testWidgets('deep link navigates to product screen', (tester) async {
await tester.pumpWidget(
MaterialApp.router(routerConfig: router),
);
router.go('/product/456');
await tester.pumpAndSettle();
expect(find.byType(ProductScreen), findsOneWidget);
});
}
Tolinku SDK 연동 방법은 및 Flutter SDK 문서. 라우팅 구조는 딥 링크 라우팅 가이드.
딥 링킹 팁을 메일로 받아 보세요
일주일에 한 번만 보내요. 스팸은 없어요.