URL 또는 경로에 따라 어떤 화면을 보여줄지 결정하는 규칙.
앱에서 "이 경로로 가면 이 화면" 을 매핑해두는 것.
/home → 홈 화면
/login → 로그인 화면
/profile → 프로필 화면
특정 조건에 따라 원래 요청한 경로 대신 다른 경로로 보내는 것.
라우터 안에서 조건 분기처럼 동작함.
/profile 접근 시도
→ 로그인 상태? → /profile 진입 허용
→ 비로그인? → /login 으로 리다이렉트
Flutter에서 라우팅은 go_router 패키지를 가장 많이 씀.
final router = GoRouter(
initialLocation: '/home',
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomePage(),
),
GoRoute(
path: '/login',
builder: (context, state) => const LoginPage(),
),
GoRoute(
path: '/profile',
builder: (context, state) => const ProfilePage(),
),
],
);
final router = GoRouter(
initialLocation: '/home',
redirect: (context, state) {
final isLoggedIn = FirebaseAuth.instance.currentUser != null;
final isLoginPage = state.matchedLocation == '/login';
if (!isLoggedIn && !isLoginPage) return '/login'; // 비로그인 → 로그인 페이지로
if (isLoggedIn && isLoginPage) return '/home'; // 이미 로그인 → 홈으로
return null; // 리다이렉트 없음, 그대로 진행
},
routes: [ ... ],
);
redirect에서 null 반환 → 현재 경로 그대로 진행redirect에서 경로 반환 → 해당 경로로 이동// 이동 (현재 스택에 쌓기)
context.push('/profile');
// 이동 (현재 화면 교체, 뒤로 가기 불가)
context.go('/home');
// 뒤로 가기
context.pop();
| 메서드 | 동작 | 뒤로 가기 |
|---|---|---|
push | 스택에 추가 | 가능 |
go | 스택 교체 | 불가 |
pop | 이전 화면으로 | - |
서버나 웹에서도 리다이렉트 개념은 동일하게 쓰임.
| 코드 | 의미 | 용도 |
|---|---|---|
| 301 | 영구 이동 | URL이 영구적으로 바뀐 경우 |
| 302 | 임시 이동 | 로그인 후 원래 페이지로 돌아갈 때 |
| 307 | 임시 이동 (메서드 유지) | POST 요청을 그대로 다른 곳으로 |
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/old-path")
def old_path():
return RedirectResponse(url="/new-path", status_code=301)
| 라우터 | 리다이렉트 | |
|---|---|---|
| 역할 | 경로 → 화면 매핑 | 조건에 따라 경로 변경 |
| 시점 | 앱 초기화 시 등록 | 경로 진입 직전 실행 |
| 반환값 | 화면 위젯 | 새 경로 or null |
라우터는 지도, 리다이렉트는 "이 길은 막혔으니 저쪽으로 가세요" 같은 우회로
로그인 여부에 따른 화면 분기는 리다이렉트로 처리하는 게 깔끔하고,
클라이언트 코드 곳곳에서 분기 처리하는 것보다 라우터 한 곳에서 관리하는 게 훨씬 유지보수가 편하다.