[TIL] Day 49 go_router

현서·6일 전

[TIL] Flutter 9기

목록 보기
61/65

📝 go_router

✏️ go_router란?

Flutter 공식 라우팅 패키지
선언형(Declarative) + URL 기반 라우팅을 지원

  • 모바일 / 웹 공통
  • 딥링크 지원
  • 인증·권한 분기 쉬움
  • Navigator의 복잡함 해결

✏️ go_router를 쓰는 이유

화면 이동 코드가 분산됨
뒤로 가기 / 분기 처리 복잡
웹 URL 대응 어려움

go_router 장점

라우트 중앙 관리
URL = 화면 상태
redirect로 흐름 제어 가능
구조가 명확함

✏️ 핵심 개념 정리

개념설명
GoRouter전체 라우터 설정
GoRoute개별 화면 라우트
ShellRoute공통 레이아웃 유지
pathURL 경로
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');

✏️ Path Parameter (URL 파라미터)

라우트 정의

GoRoute(
  path: '/detail/:id',
  builder: (context, state) {
    final id = state.pathParameters['id']!;
    return DetailPage(id: id);
  },
);

이동

context.push('/detail/3');

✏️ Query Parameter

이동

context.push('/search?keyword=cat&page=2');

받기

final keyword = state.uri.queryParameters['keyword'];
final page = state.uri.queryParameters['page'];

✏️ Nested Route (중첩 라우트)

GoRoute(
  path: '/home',
  builder: (context, state) => HomePage(),
  routes: [
    GoRoute(
      path: 'detail',
      builder: (context, state) => DetailPage(),
    ),
  ],
);

실제 URL: /home/detail

✏️ ShellRoute (공통 레이아웃)

목적

  • AppBar / BottomNav 고정
  • body 영역만 교체
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 vs Navigator 비교

항목go_routerNavigator
선언형
URL
딥링크
웹 대응강함약함
흐름 제어쉬움어려움

0개의 댓글