안녕하세요.
이번 글에서는 플러터 router 종류에 대해서 간략히 알아보고 비교해보겠습니다.
- flutter_bloc [https://bloclibrary.dev/#/recipesflutternavigation]
- GetX [https://github.com/jonataslaw/getx/blob/master/documentation/kr_KO/dependency_management.md]
- Go_router [https://pub.dev/packages/go_router]
- Notifier와 Inherited [https://flutter.github.io/samples/navigation_and_routing.html]
1 ] flutter_bloc
bloc의 경우 항상 state 상태를 받기 위해서 전체 앱을 BlocProvider, MultiBlocProvider로 감싸고 시작하여 하위 위젯에서도 언제든지 변화를 알수 있도록 합니다.
이렇게 하면 하위 페이지였던 PageA에서 BlocListener를 통해 Bloc, State를 호출가능하게 됩니다.
void main() {
runApp(
BlocProvider(
create: (context) => MyBloc(),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (context) => PageA(),
'/pageB': (context) => PageB(),
},
initialRoute: '/',
);
}
}
class PageA extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocListener<MyBloc, MyState>(
listener: (context, state) {
if (state is StateB) {
Navigator.of(context).pushNamed('/pageB');
}
},
child: Scaffold(
)
// ...
}
}
2 ] GexX
getx의 경우, GetMaterialApp과 GetPage로 구성되어있는데요. 공식 문서의 소개처럼 inheritedWidget 없이 Get.put<SomeClass>() 의 방법으로 인스턴스화 한 다음에, 하위 페이지에서 Get.find<SomeClass>()의 호출로 간단히 종속된 클래스를 호출할 수 있습니다.
Get은 Provider context, inheritedWidget 없이 단 1줄의 코드로 Bloc 나 Controller 같은 클래스를 찾을수 있는 간단하고 강력한 종속성 관리자가 있습니다.
void main() {
runApp(
GetMaterialApp(
unknownRoute: GetPage(name: '/notfound', page: () => UnknownRoutePage()),
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => MyHomePage()),
GetPage(name: '/second', page: () => Second()),
],
)
);
}
혹은 GetPage에서 바인딩을 통해 하위 위젯들에서 종속된 클래스를 호출가능하게 하는 방법도 있습니다.
{
...
static final routes = [
GetPage(
name: Routes.HOME,
page: () => const HomeView(),
binding: HomeBinding(),
children: [
GetPage(
name: Routes.COUNTRY,
page: () => const CountryView(),
children: [
GetPage(
name: Routes.DETAILS,
page: () => const DetailsView(),
),
],
),
],
),
];
...
}
class HomeBinding extends Binding {
@override
List<Bind> dependencies() {
return [
Bind.lazyPut<IHomeProvider>(() => HomeProvider()),
Bind.lazyPut<IHomeRepository>(() => HomeRepository(provider: Get.find())),
Bind.lazyPut(() => HomeController(homeRepository: Get.find())),
];
}
}
3 ] go_router
https://github.com/flutter/packages/tree/main/packages/go_router/example/lib
위 링크에서 go_router로 구현된 각각의 예시코드를 확인할수 있는데요.
클래스 | 설명 |
class StreamAuth
|
유저인증정보를 흉내낸 Stream class |
class StreamAuthNotifier extends ChangeNotifier
|
인증정보가 바뀔때마다 (onCurrentUserChanged),
notifyListeners 를 통해 상속된 ChangeNotifier 호출
|
class StreamAuthScope extends InheritedNotifier<StreamAuthNotifier>
|
위에서 상속받은 notifier의 streamAuth 정보를 하위트리의 위젯으로 넘겨주는 역할 |
// async_redirection.dart
void main() => runApp(StreamAuthScope(child: App()));
/// A scope that provides [StreamAuth] for the subtree.
class StreamAuthScope extends InheritedNotifier<StreamAuthNotifier> {
/// Creates a [StreamAuthScope] sign in scope.
StreamAuthScope({
super.key,
required super.child,
}) : super(
notifier: StreamAuthNotifier(),
);
/// Gets the [StreamAuth].
static StreamAuth of(BuildContext context) {
return context
.dependOnInheritedWidgetOfExactType<StreamAuthScope>()!
.notifier!
.streamAuth;
}
}
위와 같이 App() 을 SteamAuthScope로 감싸두었기 때문에 StreamAuth가 바뀔때 하위 트리에서 모두 확인이 가능하고
아래과 같은 방법으로 하위 페이지에서 정보를 호출할 수 있습니다.
- router의 redirect: final bool loggedIn = await StreamAuthScope.of(context).isSignedIn();
- homepage하위 페이지: final StreamAuth info = StreamAuthScope.of(context);
'IT-dev' 카테고리의 다른 글
[Flutter] VS Code에서 Google Duet AI 적용하기 (1) | 2024.01.06 |
---|---|
[Flutter] adaptive 위젯 종류 (0) | 2023.11.06 |
Fluttre news toolkit Build Error Troubleshooting (0) | 2023.09.05 |
YouTube Data API Audit & Quota Extension 후기 (0) | 2022.12.21 |
[flutter] 한번에 플러터 앱 만들기 #2 - 플러터 로그인 버튼 구현 (0) | 2022.12.05 |
댓글