2023. 12. 23. 20:25ㆍFlutter
GetX를 사용하지 않게 되면서 라우팅 라이브러리로 gorouter를 사용하게 되었다
https://pub.dev/packages/go_router
go_router | Flutter Package
A declarative router for Flutter based on Navigation 2 supporting deep linking, data-driven routes and more
pub.dev
GoRouter 설정하기
설치를 한 후 초기 세팅을 해줘야 한다
Main.dart에서 MaterialApp() 대신 MaterialApp.router()으로
class App extends ConsumerWidget {
const App({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp.router(
builder: (context, widget) {
return Text("APP");
},
);
}
}
그다음 GoRouter 객체를 만들어준다
routes에 페이지로 쓸 것들을 GoRoute로 넣는다
// app_router.dart
GoRouter appRouter = GoRouter(
initialLocation: '/',
routes: <GoRoute>[
GoRoute(
path: '/',
name: 'home',
builder: (context, state) => const Home(),
),
GoRoute(
path: '/calendar',
name: 'calendar',
builder: (context, state) => const Calendar(),
),
GoRoute(
path: '/feed',
name: 'feed',
builder: (context, state) => const Feed(),
),
GoRoute(
path: '/travel',
name: 'travel',
builder: (context, state) => const Travel(),
),
GoRoute(
path: '/my_page',
name: 'myPage',
builder: (context, state) => const MyPage(),
),
],
);
initialLocation을 '/'로 설정해 첫 페이지를 home으로 만들어줬다
만들어진 GoRouter를 MaterialApp.router의 routerConfig에 추가한다
return MaterialApp.router(
routerConfig: appRouter,
builder: (context, widget) {
...
이제 페이지 이동을 할 수 있다!
페이지 이동
페이지를 이동하는 방법에는 go와 push가 있다
go()는 라우트 스택에 쌓이지 않는다
context.go("/a")
context.goNamed(routeName)
push()는 라우스 스택에 쌓인다. 그래서 뒤로 가기 버튼이 생기게 된다.
context.push("/a")
context.pushNamed(routeName)
pop()을 사용해 뒤로갈 수 있다
context.pop()
페이지 정보
현재 라우터의 name이나 path를 받아오려면
GoRouterState.of(context).path
GoRouterState.of(context).name
를 사용하면 된다
Redirect
페이지를 제한하기 위해선 redirect를 넣어주면 된다
GoRouter appRouter = GoRouter(
initialLocation: '/',
routes: <GoRoute>[
...
],
redirect: (context, state) {
final loggedIn = storage.read('user');
final visiblePages = state.fullPath == '/' || state.fullPath == '/feed';
if (loggedIn == null && !visiblePages) return '/login';
return null;
},
);
loggedIn을 통해 storage에 있는 유저를 확인한다. 이 유저는 로그인을 했으면 저장되어 있다.
visiblePages는 로그인하지않고 볼 수 있는 페이지들이다
로그인 하지 않은 상태로 회원이 볼 수 없는 페이지를 접근한다면 로그인 페이지로 리다이렉트 시킨다
그 외 경우는 원래 가려던 페이지로 이동한다
'Flutter' 카테고리의 다른 글
[Flutter] 프로젝트에 폰트 적용하기 (0) | 2024.01.04 |
---|---|
GoRouter에서 페이지 이동 transition 설정하기 (0) | 2023.12.24 |
GestureDetector의 터치 범위 (0) | 2023.12.13 |
addPostFrameCallback 사용하기 (0) | 2023.12.13 |
[Riverpod] ref가 없는 곳에서 ref 쓰기? (0) | 2023.12.08 |