Flutter 공식 라우팅 패키지
선언형(Declarative) + URL 기반 라우팅을 지원
화면 이동 코드가 분산됨
뒤로 가기 / 분기 처리 복잡
웹 URL 대응 어려움
라우트 중앙 관리
URL = 화면 상태
redirect로 흐름 제어 가능
구조가 명확함
| 개념 | 설명 |
|---|---|
GoRouter | 전체 라우터 설정 |
GoRoute | 개별 화면 라우트 |
ShellRoute | 공통 레이아웃 유지 |
path | URL 경로 |
builder | 화면 생성 |
state | 라우팅 상태 정보 |
Router 생성
final router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomePage(),
),
],
);
MaterialApp 연결
MaterialApp.router(
routerConfig: router,
);
go vs push
| 메서드 | 특징 | 사용처 |
|---|---|---|
context.go() | 스택 초기화 | 탭 이동 |
context.push() | 스택에 추가 | 상세 페이지 |
context.go('/home');
context.push('/detail');
라우트 정의
GoRoute(
path: '/detail/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
return DetailPage(id: id);
},
);
이동
context.push('/detail/3');
이동
context.push('/search?keyword=cat&page=2');
받기
final keyword = state.uri.queryParameters['keyword'];
final page = state.uri.queryParameters['page'];
GoRoute(
path: '/home',
builder: (context, state) => HomePage(),
routes: [
GoRoute(
path: 'detail',
builder: (context, state) => DetailPage(),
),
],
);
실제 URL: /home/detail
목적
ShellRoute(
builder: (context, state, child) {
return Scaffold(
body: child,
bottomNavigationBar: BottomNav(),
);
},
routes: [
GoRoute(
path: '/home',
builder: (context, state) => HomePage(),
),
GoRoute(
path: '/profile',
builder: (context, state) => ProfilePage(),
),
],
);
| 항목 | go_router | Navigator |
|---|---|---|
| 선언형 | ⭕ | ❌ |
| URL | ⭕ | ❌ |
| 딥링크 | ⭕ | ❌ |
| 웹 대응 | 강함 | 약함 |
| 흐름 제어 | 쉬움 | 어려움 |